如何在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)”。
其他回答
正如许多人已经指出的那样,如果需要对两个列表应用完全相同的处理方式,itertools.chain()是一种方法。在我的例子中,我有一个标签和一个标志,这两个列表不同,所以我需要一些稍微复杂一些的东西。事实证明,幕后itertools.chain()只执行以下操作:
for it in iterables:
for element in it:
yield element
(参见https://docs.python.org/2/library/itertools.html),所以我从这里得到了灵感,并写了一些东西:
for iterable, header, flag in ( (newList, 'New', ''), (modList, 'Modified', '-f')):
print header + ':'
for path in iterable:
[...]
command = 'cp -r' if os.path.isdir(srcPath) else 'cp'
print >> SCRIPT , command, flag, srcPath, mergedDirPath
[...]
这里要理解的要点是,列表只是可迭代的一种特殊情况,它是与任何其他对象一样的对象;这是为了。。。python中的in循环可以与元组变量一起工作,因此同时循环多个变量很简单。
这很简单,我认为它甚至在教程中显示了:
>>> listone = [1,2,3]
>>> listtwo = [4,5,6]
>>>
>>> listone + listtwo
[1, 2, 3, 4, 5, 6]
如果不能使用加号运算符(+),则可以使用运算符导入:
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]
使用+运算符组合列表:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
输出:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
提供的解决方案仅针对单个列表。如果列表中有列表,并且需要合并相应的列表,则通过for循环执行“+”操作即可。
a = [[1,2,3], [4,5,6]]
b = [[0,1,2], [7,8,9]]
for i in range(len(a)):
cc.append(a[i] + b[i])
输出:[[1,2,3,0,1,2],[4,5,6,7,8,9]