在下面的程序中,嵌套方法和链式方法有什么区别/链从\u 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']
chain
各种方法不是问题所在,您的问题归结为:一旦你迭代了你的
zip_iter
变量,第二次它什么也不会产生,这就是zip
的工作原理(range
可以被多次迭代,例如,但那是因为它把整数作为参数,而不是iterables,第二次运行时可能会用尽……)上一个示例之所以有效,是因为您正在创建一个新的
zip
对象。你知道吗相关问题 更多 >
编程相关推荐