如何在Python中连接两个列表?
例子:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
预期结果:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
如何在Python中连接两个列表?
例子:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
预期结果:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
当前回答
对于列表数量较少的情况,您可以简单地将列表添加到一起或使用就地解包(Python-3.5+版本中提供):
In [1]: listone = [1, 2, 3]
...: listtwo = [4, 5, 6]
In [2]: listone + listtwo
Out[2]: [1, 2, 3, 4, 5, 6]
In [3]: [*listone, *listtwo]
Out[3]: [1, 2, 3, 4, 5, 6]
对于列表数量较多的情况,可以使用itertools模块中的chain.from_iterable()1函数,这是一种更通用的方法。此外,根据这个答案,这个函数是最好的;或者至少是一种非常好的方式来展开嵌套列表。
>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1.注意,“chain.from_iterable()”在Python 2.6及更高版本中可用。在其他版本中,使用“chain(*l)”。
其他回答
如果不能使用加号运算符(+),则可以使用运算符导入:
import operator
listone = [1,2,3]
listtwo = [4,5,6]
result = operator.add(listone, listtwo)
print(result)
>>> [1, 2, 3, 4, 5, 6]
或者,您也可以使用__add__dunder函数:
listone = [1,2,3]
listtwo = [4,5,6]
result = list.__add__(listone, listtwo)
print(result)
>>> [1, 2, 3, 4, 5, 6]
对于列表数量较少的情况,您可以简单地将列表添加到一起或使用就地解包(Python-3.5+版本中提供):
In [1]: listone = [1, 2, 3]
...: listtwo = [4, 5, 6]
In [2]: listone + listtwo
Out[2]: [1, 2, 3, 4, 5, 6]
In [3]: [*listone, *listtwo]
Out[3]: [1, 2, 3, 4, 5, 6]
对于列表数量较多的情况,可以使用itertools模块中的chain.from_iterable()1函数,这是一种更通用的方法。此外,根据这个答案,这个函数是最好的;或者至少是一种非常好的方式来展开嵌套列表。
>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
1.注意,“chain.from_iterable()”在Python 2.6及更高版本中可用。在其他版本中,使用“chain(*l)”。
Python>=3.5可选:[*l1,*l2]
通过接受PEP 448引入了另一种备选方案,值得一提。
名为Additional Unpacking Generalization的PEP在Python中使用星号*表达式时,通常会减少一些语法限制;使用它,连接两个列表(适用于任何可迭代的列表)现在也可以通过以下方式完成:
>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> joined_list = [*l1, *l2] # unpack both iterables in a list literal
>>> print(joined_list)
[1, 2, 3, 4, 5, 6]
此功能是为Python 3.5定义的,但尚未向后移植到3.x系列的早期版本。在不支持的版本中,将引发SyntaxError。
与其他方法一样,这也会创建相应列表中元素的浅拷贝。
这种方法的好处是,你真的不需要列表来执行它;任何可迭代的都可以。如PEP中所述:
这也是一种更易读的方法,可以将可迭代项相加为列表,例如my_list+list(my_tuple)+list(my_range),现在相当于[*my_list,*my_tuple,*my_range]。
因此,虽然添加+会由于类型不匹配而引发TypeError:
l = [1, 2, 3]
r = range(4, 7)
res = l + r
以下情况不会:
res = [*l, *r]
因为它将首先解压缩可迭代内容,然后简单地从内容创建一个列表。
如果您需要使用复杂的排序规则合并两个有序列表,您可能需要像下面的代码一样自行滚动(使用简单的排序规则以提高可读性:-)。
list1 = [1,2,5]
list2 = [2,3,4]
newlist = []
while list1 and list2:
if list1[0] == list2[0]:
newlist.append(list1.pop(0))
list2.pop(0)
elif list1[0] < list2[0]:
newlist.append(list1.pop(0))
else:
newlist.append(list2.pop(0))
if list1:
newlist.extend(list1)
if list2:
newlist.extend(list2)
assert(newlist == [1, 2, 3, 4, 5])
您可以使用在列表对象上定义的append()方法:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)