print('__next__' in dir(range(12))) # 查看'__next__'是不是在range()方法执行之后内部是否有__next__ print('__iter__' in dir(range(12))) # 查看'__next__'是不是在range()方法执行之后内部是否有__iter__
from collections import Iterator print(isinstance(range(100000000),Iterator)) # 验证range执行之后得到的结果不是一个迭代器
# 初识生成器二 def produce(): """生产衣服""" for i in range(2000000): yield "生产了第%s件衣服"%i
product_g = produce() print(product_g.__next__()) # 要一件衣服 print(product_g.__next__()) # 再要一件衣服 print(product_g.__next__()) # 再要一件衣服 num = 0 for i in product_g: # 要一批衣服,比如5件 print(i) num +=1 if num == 5: break
import time def tail(filename): f = open(filename) f.seek(0, 2) # 从文件末尾算起 while True: line = f.readline() # 读取文件中新的文本行 if not line: time.sleep(0.1) continue yield line
tail_g = tail('tmp') for line in tail_g: print(line)
计算移动平均值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
def averager(): total = 0.0 count = 0 average = None while True: term = yield average total += term count += 1 average = total/count
list = ['%s' %i for i in range(10)] # 列表推导式 laomuji = ('%s' %i for i in range(10)) # 生成器表达式 print(laomuji) print(next(laomuji)) # next本质就是调用__next__ print(laomuji.__next__()) print(next(laomuji))
variable = [out_exp_res for out_exp in input_list if out_exp == 2] out_exp_res: 列表生成元素表达式,可以是有返回值的函数。 for out_exp in input_list:迭代input_list将out_exp传入out_exp_res表达式中。 if out_exp == 2:根据条件过滤哪些值可以。
列表推导式[]
例一:30以内所有能被3整除的数
1 2
multiples = [i for i in range(30) if i % 3 is 0] print(multiples) # Output: [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
例二:30以内所有能被3整除的数的平方
1 2 3 4
def squared(x): return x*x multiples = [squared(i) for i in range(30) if i % 3 is 0] print(multiples)
例三:找到嵌套列表中名字含有两个‘e’的所有名字
1 2 3
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'], ['Alice', 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']] print([name for lst in names for name in lst if name.count('e') >= 2]) # 注意遍历顺序,这是实现的关键
字典推导式{}
例一:将一个字典的key和value对调
1 2 3
mcase = {'a': 10, 'b': 34} mcase_frequency = {mcase[k]: k for k in mcase} print(mcase_frequency)
例二:合并大小写对应的value值,将k统一成小写
1 2 3
mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3} mcase_frequency = {k.lower(): mcase.get(k.lower(), 0) + mcase.get(k.upper(), 0) for k in mcase.keys()} print(mcase_frequency)
集合推导式{}
例:计算列表中每个值的平方,自带去重功能
1 2 3
squared = {x**2 for x in [1, -1, 2]} print(squared) # Output: set([1, 4])