如何在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]
当前回答
您可以简单地使用+或+=运算符,如下所示:
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
Or:
c = []
a = [1, 2, 3]
b = [4, 5, 6]
c += (a + b)
此外,如果希望合并列表中的值是唯一的,可以执行以下操作:
c = list(set(a + b))
其他回答
还可以使用itertools.chain()创建一个生成器,简单地迭代两个列表中的项目。这允许您将列表(或任何可迭代的)链接在一起进行处理,而无需将项目复制到新列表:
import itertools
for item in itertools.chain(listone, listtwo):
# Do something with each list item
a = [1, 2, 3]
b = [4, 5, 6]
c = a + b
print(c)
输出
>>> [1, 2, 3, 4, 5, 6]
在上面的代码中,“+”运算符用于将两个列表连接成一个列表。
另一种解决方案
a = [1, 2, 3]
b = [4, 5, 6]
c = [] # Empty list in which we are going to append the values of list (a) and (b)
for i in a:
c.append(i)
for j in b:
c.append(j)
print(c)
输出
>>> [1, 2, 3, 4, 5, 6]
用于连接列表的最常见方法是加号运算符和内置方法append,例如:
list = [1,2]
list = list + [3]
# list = [1,2,3]
list.append(3)
# list = [1,2,3]
list.append([3,4])
# list = [1,2,[3,4]]
对于大多数情况,这都会起作用,但如果添加了列表,append函数将不会扩展列表。因为这是不期望的,所以可以使用另一个名为extend的方法。它应适用于以下结构:
list = [1,2]
list.extend([3,4])
# list = [1,2,3,4]
这很简单,我认为它甚至在教程中显示了:
>>> listone = [1,2,3]
>>> listtwo = [4,5,6]
>>>
>>> listone + listtwo
[1, 2, 3, 4, 5, 6]
使用简单的列表理解:
joined_list = [item for list_ in [list_one, list_two] for item in list_]
它具有使用Additional Unpacking Generalization的最新方法的所有优点-即,您可以以这种方式连接任意数量的不同可迭代项(例如,列表、元组、范围和生成器)-并且它不限于Python 3.5或更高版本。