在下面的程序中,当我们得到不同的输出时,嵌套方法与chain/chain.from_iterable之间的区别是什么。
“”
编写一个python程序,在列表的每个元素之前插入一个元素。
“”
例如:
from itertools import repeat, chain
def insertElementApproach2():
color = ['Red', 'Green', 'Black']
print("The pair element:")
zip_iter = zip(repeat('a'),color)
print((list(zip_iter)))
print("The combined element using chain:")
print(list(chain(zip_iter)))
print("The combined element using chain.from_iterable:")
print(list(chain(zip_iter)))
print("Using the nested approach:")
print(list(chain.from_iterable(zip(repeat('a'),color))))
Output:
The pair element:
[('a', 'Red'), ('a', 'Green'), ('a', 'Black')]
The combined element using chain:
[]
The combined element using chain.from_iterable:
[]
Using the nested approach:
['a', 'Red', 'a', 'Green', 'a', 'Black']