如何在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(set(listone) | set(listtwo))
上述代码不保留顺序,并从每个列表中删除重复项(但不从连接列表中删除)。
其他回答
使用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]
使用+运算符组合列表:
listone = [1, 2, 3]
listtwo = [4, 5, 6]
joinedlist = listone + listtwo
输出:
>>> joinedlist
[1, 2, 3, 4, 5, 6]
正如许多人已经指出的那样,如果需要对两个列表应用完全相同的处理方式,itertools.chain()是一种方法。在我的例子中,我有一个标签和一个标志,这两个列表不同,所以我需要一些稍微复杂一些的东西。事实证明,幕后itertools.chain()只执行以下操作:
for it in iterables:
for element in it:
yield element
(参见https://docs.python.org/2/library/itertools.html),所以我从这里得到了灵感,并写了一些东西:
for iterable, header, flag in ( (newList, 'New', ''), (modList, 'Modified', '-f')):
print header + ':'
for path in iterable:
[...]
command = 'cp -r' if os.path.isdir(srcPath) else 'cp'
print >> SCRIPT , command, flag, srcPath, mergedDirPath
[...]
这里要理解的要点是,列表只是可迭代的一种特殊情况,它是与任何其他对象一样的对象;这是为了。。。python中的in循环可以与元组变量一起工作,因此同时循环多个变量很简单。
你也可以使用sum。
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> sum([a, b], [])
[1, 2, 3, 4, 5, 6]
>>>
这适用于任何长度和任何元素类型的列表:
>>> a = ['a', 'b', 'c', 'd']
>>> b = [1, 2, 3, 4]
>>> c = [1, 2]
>>> sum([a, b, c], [])
['a', 'b', 'c', 'd', 1, 2, 3, 4, 1, 2]
>>>
我添加[]的原因是,start参数默认设置为0,因此它在列表中循环并添加到start,但0+[1,2,3]会产生错误,因此如果我们将start设置为[]。它将添加到[],并且[]+[1,2,3]将按预期工作。
您还可以使用list.exextend()方法将列表添加到另一个列表的末尾:
listone = [1,2,3]
listtwo = [4,5,6]
listone.extend(listtwo)
如果要保持原始列表的完整性,可以创建一个新的列表对象,并将两个列表都扩展到该对象:
mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)