繁体   English   中英

使用一对一的元素将两个列表合并为一个

[英]combine two lists into one using one by one element

如何使用一个一元素将两个列表合并为一个,如下所示:

list1 = ['a','c','e']

list2 = ['apple','carrot','elephant']

result = ['a', 'apple', 'c', 'carrot', 'e', 'elephant']

试用版

result = [(x,y) for x,y in zip(list1,list2)]
print result

但是它们在元组中,任何更轻松的灵魂都可以期待...

您可以使用双重循环列表理解:

>>> list1 = ['a','c','e']
>>> list2 = ['apple','carrot','elephant']
>>> [x for z in zip(list1, list2) for x in z]
['a', 'apple', 'c', 'carrot', 'e', 'elephant']
In [4]: list1 = ['a','c','e']

In [5]: list2 = ['apple','carrot','elephant']

In [6]: list(itertools.chain.from_iterable(zip(list1, list2)))
Out[6]: ['a', 'apple', 'c', 'carrot', 'e', 'elephant']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM