如何在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]
当前回答
您还可以使用list.exextend()方法将列表添加到另一个列表的末尾:
listone = [1,2,3]
listtwo = [4,5,6]
listone.extend(listtwo)
如果要保持原始列表的完整性,可以创建一个新的列表对象,并将两个列表都扩展到该对象:
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)
其他回答
您可以使用在列表对象上定义的append()方法:
mergedlist =[]
for elem in listone:
mergedlist.append(elem)
for elem in listtwo:
mergedlist.append(elem)
组合列表列表的一种非常简洁的方法是
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]
值得注意的是,itertools.chain函数接受可变数量的参数:
>>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
>>> [i for i in itertools.chain(l1, l2)]
['a', 'b', 'c']
>>> [i for i in itertools.chain(l1, l2, l3)]
['a', 'b', 'c', 'd', 'e', 'f']
如果输入是可迭代的(元组、列表、生成器等),则可以使用from_iteable类方法:
>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']
我假设您需要以下两种方法之一:
保留重复元素
这很容易。就像字符串一样连接:
def concat_list(l1,l2):
l3 = l1+l2
return l3
接下来,如果要消除重复元素
def concat_list(l1,l2):
l3 = []
for i in [l1,l2]:
for j in i:
if j not in l3:
# Check if element exists in final list, if no then add element to list
l3.append(j)
return l3
您还可以使用list.exextend()方法将列表添加到另一个列表的末尾:
listone = [1,2,3]
listtwo = [4,5,6]
listone.extend(listtwo)
如果要保持原始列表的完整性,可以创建一个新的列表对象,并将两个列表都扩展到该对象:
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)