未分类

Python - yield from 的作用

1
2
3
4
5
6
7
8
9
10
11
12
# 作用:递归遍历多层嵌套列表内的值到一个列表
# yield from iterable本质上等于for item in iterable: yield item的缩写版,yield from的作用对象是iterable
def recursive(ns):
# if type(ns) is list:
if isinstance(ns, list):
for i in ns:
yield from recursive(i) # 此处的yield from 可以理解为起到了一个管道的传递作用,不断地将内层的iterable生成的值传递出去
else:
yield ns # 如果上面递归的时候不加yield from,这里yield不会有任何作用

ns1 = [[1,2,3],[[4,5],[6,7,8]],[9,10], 11]
list(recursive(ns1)) # [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

参考:

python yield 和 yield from用法总结

Python 3: Using “yield from” in Generators - Part 1

分享到