如何在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]
>>>
其他回答
使用+运算符组合列表:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
输出:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
这很简单,我认为它甚至在教程中显示了:
>>> 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或更高版本。
您可以使用在列表对象上定义的append()方法:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)
使用Python 3.3+,您可以从以下位置使用yield:
listone = [1,2,3]
listtwo = [4,5,6]
def merge(l1, l2):
yield from l1
yield from l2
>>> list(merge(listone, listtwo))
[1, 2, 3, 4, 5, 6]
或者,如果您希望支持任意数量的迭代器:
def merge(*iters):
for it in iters:
yield from it
>>> list(merge(listone, listtwo, 'abcd', [20, 21, 22]))
[1, 2, 3, 4, 5, 6, 'a', 'b', 'c', 'd', 20, 21, 22]