推导式、生成器与切片
一、实验要求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)
到此这篇关于Python 推导式、生成器与切片的文章就介绍到这了,更多相关Python 推导式、生成器与切片内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!