如何在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]
当前回答
另一种方式:
>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]
>>> joinedlist = [*listone, *listtwo]
>>> joinedlist
[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]
使用简单的列表理解:
joined_list = [item for list_ in [list_one, list_two] for item in list_]
它具有使用Additional Unpacking Generalization的最新方法的所有优点-即,您可以以这种方式连接任意数量的不同可迭代项(例如,列表、元组、范围和生成器)-并且它不限于Python 3.5或更高版本。
list(set(listone) | set(listtwo))
上述代码不保留顺序,并从每个列表中删除重复项(但不从连接列表中删除)。
您可以简单地使用+或+=运算符,如下所示:
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))
使用+运算符组合列表:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
输出:
>>> joinedlist
[1, 2, 3, 4, 5, 6]