Py学习  »  Python

编写一个python程序,在列表的每个元素之前插入一个元素

kushi s • 5 年前 • 1473 次点击  

在下面的程序中,当我们得到不同的输出时,嵌套方法与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']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43017
 
1473 次点击  
文章 [ 1 ]  |  最新文章 5 年前