如何在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]
当前回答
使用简单的列表理解:
joined_list = [item for list_ in [list_one, list_two] for item in list_]
它具有使用Additional Unpacking Generalization的最新方法的所有优点-即,您可以以这种方式连接任意数量的不同可迭代项(例如,列表、元组、范围和生成器)-并且它不限于Python 3.5或更高版本。
其他回答
另一种方式:
>>> listone = [1, 2, 3]
>>> listtwo = [4, 5, 6]
>>> joinedlist = [*listone, *listtwo]
>>> joinedlist
[1, 2, 3, 4, 5, 6]
>>>
如果您需要使用复杂的排序规则合并两个有序列表,您可能需要像下面的代码一样自行滚动(使用简单的排序规则以提高可读性:-)。
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])
可以使用集合获取唯一值的合并列表
mergedlist = list(set(listone + listtwo))
这个问题直接询问加入两个列表。然而,即使您正在寻找一种连接多个列表的方法(包括连接零个列表的情况),它在搜索中也非常高。
我认为最好的选择是使用列表综合:
>>> a = [[1,2,3], [4,5,6], [7,8,9]]
>>> [x for xs in a for x in xs]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
还可以创建生成器:
>>> map(str, (x for xs in a for x in xs))
['1', '2', '3', '4', '5', '6', '7', '8', '9']
旧答案
考虑这种更通用的方法:
a = [[1,2,3], [4,5,6], [7,8,9]]
reduce(lambda c, x: c + x, a, [])
将输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
注意,当a为[]或[[1,2,3]]时,这也可以正常工作。
然而,使用itertools可以更有效地实现这一点:
a = [[1,2,3], [4,5,6], [7,8,9]]
list(itertools.chain(*a))
如果您不需要列表,而只需要一个可迭代的列表,请省略list()。
使现代化
Patrick Collins在评论中提出的备选方案也适用于您:
sum(a, [])
组合列表列表的一种非常简洁的方法是
list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
reduce(list.__add__, list_of_lists)
这给了我们
[1, 2, 3, 4, 5, 6, 7, 8, 9]