Python 推导式、生成器与切片
BoBo yeah 人气:0推导式、生成器与切片
一、实验要求
1.理解并掌握序列中的常用操作。
2.理解并掌握推导式、切片等用法并能解决实际问题。
二、实验内容
1,编写程序,测试字符的出现频率。
#use dict method1 data = ['a','2',2,3,6,'2','b',4,7,2,'6','d',6,'a','z'] frequences=dict() for item in data: if item in frequences: frequences[item] += 1 else: frequences[item] = 1 print frequences
#use dict method2 frequences = dict() for item in data: frequences[item] = frequences.get(item,0) + 1 print frequences
#use defaultdict from collections import defaultdict frequences = defaultdict(int) for item in data: frequences[item] += 1 print frequences.items()
#use set and list type count_set = set(data) count_list = [] for item in count_set: count_list.append((item,data.count(item))) print count_list
#use collections.Counter from collections import Counter frequences = Counter(data) print frequences.items() print list(frequences.elements()) #list all the elements print frequences.most_common(3)
2, 编写程序求100以内的所有奇数的和。
sum = 0 for i in range(1,100,2): sum = sum + i print(sum)
3,编写程序,生成包含30个随机整数的列表,然后对偶数下标的元素降序排列,奇数下标的元素不变。
import random x = [random.randint(0,100) for i in range(30)] #print(x) 打印x看看原列表 y = x[::2] #print(y) 打印偶数坐标 y.sort(reverse=True) x[::2] = y print(x)
加载全部内容