Python中的合并列表 [英] Merge Lists in Python
问题描述
我有2个列表:(列表1,列表2),我需要将这些列表合并到另一个包含list1
和list2
的列表中,顺序如下:
I have 2 lists: (list1, list2) and I need to merge these lists to another list which contains list1
and list2
in this order:
- listNew = [list1(i),list2(i),list1(i + 1),list2(i + 1),...]
我尝试过:
listNew = list1 + list2
for i in listNew:
listNew.append(i)
hranyNew.append(pocetHran/2+i)
但出现错误:
+不支持的操作数类型:"int"和"str"
unsupported operand type(s) for +: 'int' and 'str'
还有另一个问题,如何将listNew[i]
和listNew[i+1]
与listNew[i+2]
和listNew[i+3]
进行比较?
And another question, how can I compare listNew[i]
and listNew[i+1]
with listNew[i+2]
and listNew[i+3]
?
换句话说,我需要将所有相邻对与pair+1
,2
等进行比较.
谢谢!
In another words, I need to compare all adjacent pairs with pair+1
, 2
and so on..
Thanks!
推荐答案
I want to point out the very convenient itertools.chain()
:
from itertools import chain
list1 = ['1','2','3']
list2 = ['a','b','c']
listNew = list(chain.from_iterable(zip(list1, list2)))
# listNew = ['1', 'a', '2', 'b', '3', 'c']
您还可以将列表理解与双循环:
listNew = [y for x in zip(list1, list2) for y in x]
# listNew = ['1', 'a', '2', 'b', '3', 'c']
如果要在listNew
中连接成对的元素,那就很简单:
If you want to concatenate pairs of elements in your listNew
, that is simply:
listNew_ = [x + y for x, y in zip(list1, list2)]
# listNew_ = ['1a', '2b', '3c']
这篇关于Python中的合并列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!