编写一个Python程序在lis的每个元素之前插入一个元素

2024-04-24 03:13:40 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的程序中,嵌套方法和链式方法有什么区别/链从\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']

Tags: thefromchaingreenredelementzipiterable
1条回答
网友
1楼 · 发布于 2024-04-24 03:13:40

chain各种方法不是问题所在,您的问题归结为:

>>> a = zip([1],[2])
>>> list(a)
[(1, 2)]
>>> list(a)
[]

一旦你迭代了你的zip_iter变量,第二次它什么也不会产生,这就是zip的工作原理(range可以被多次迭代,例如,但那是因为它把整数作为参数,而不是iterables,第二次运行时可能会用尽……)

上一个示例之所以有效,是因为您正在创建一个新的zip对象。你知道吗

相关问题 更多 >