1.获取移动平均值。
def generator():
sum = 0
num = 0
count = 0
avg = 0
while 1:
num = yield avg
sum += num
count += 1
avg = sum / count
avg_g = generator()
avg_g.__next__()
a = avg_g.send(10)
a = avg_g.send(120)
a = avg_g.send(190)
a = avg_g.send(126)
print(a)
2.30以内能被3整除的数,用列表推导式。
ret = [i for i in range(30) if i % 3 == 0]
print(ret)
3.30以内能被3整除的数的平方,用列表推导式。
ret = [i**2 for i in range(30) if i % 3 == 0]
print(ret)
4.找到嵌套列表中名字含有两个‘e’的所有名字。
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
ret = [name for li in names for name in li if name.count('e') == 2]
print(ret)
5.将一个字典的key和value对调。
mcase = {'a': 10, 'b': 34}
mcase_dic = {mcase[k]: k for k in mcase}
print(mcase_dic)