def g1(iterable):
yield iterable
def g2(iterable):
yield from iterable
for value in g1(range(10)):
print(value)
for value in g2(range(10)):
print(value)
输出
range(0, 10)
0
1
2
3
4
5
6
7
8
9
from itertools import chain
my_list = [1, 2, 3]
my_dict = {
'jeff1': 'http://baidu.com',
'jeff2': 'http://google.com',
}
# 与chain等效
def my_chain(*args, **kwargs):
for my_iterable in args:
# 与yield from my_iterable等效
# for value in my_iterable:
# yield value
yield from my_iterable
for value in my_chain(my_list, my_dict, range(5, 10)):
print(value)
输出
1
2
3
jeff1
jeff2
5
6
7
8