列表生成器
生成1-101的数
a=list(range(1,101))
print(a)
a=[i for i in range(1,101)]
print(a)
展示所有文件
import os
a=[d for d in os.listdir(‘.‘)]
print(a)
将列表里的字符串变成小写 列表生成式
L = [‘Hello‘, ‘World‘, 18, ‘Apple‘, None]
L2 = [s.lower()for s in L if isinstance(s,str)]
print(L2)
生成器与迭代器
iter可以将可迭代数据转成迭代器
next迭代器可以被next不断调用
it=iter([1,2,3,4,5])
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))
能被next调用即为迭代器
生成器是特殊的迭代器
生成器 生成器不会占用内存空间只有被调用的时候会出现
a=(i for i in range(1,10))#圆括号的列表生成器
for i in a:
print(i)
yield不会结束
def get_num():
for i in range(1,10):
yield i
yield 123
for i in get_num():
print(i)
杨辉三角
def triangles():
a = [1]
# n = 1
yield a
while True:
# n = n+1
c = []
for i in range(len(a) - 1):
c.append(a[i] + a[i + 1])
b = [1] + c + [1]
a = b
yield b
for i in get_3():
print(i)
n = 0
results = []
for t in triangles():
results.append(t)
n = n + 1
if n == 10:
break
for t in results:
print(t)
python生成器与迭代器