列表推导式:
list=[num*num for num in range(1,11) if num%2==0]
print(list) #[4, 16, 36, 64, 100]
list=[char+num for num in ['1','2','3'] for char in ['a','b','c']]
print(list) #拼接数字和字符 ['1a', '1b', '1c', '2a', '2b', '2c', '3a', '3b', '3c']
生成器表达式:
将列表推导式的方括号[]改为小括号()即可创建一个生成器,通过next()调用算法实时生成元素,因此生成器占用的内存空间很小:
list=(num*num for num in range(1,11))
生成器函数:
yield关键字
def s(i):
for n in range(i):
print('before yield')
yield n*n
print('after yield')
for n in s(5):
print(n)
结果:
'''before yield
0
after yield
before yield
1
after yield
before yield
4
after yield
before yield
9
after yield
before yield
16
after yield'''
迭代器: