如何在Python中连接两个列表?

例子:

listone = [1, 2, 3]
listtwo = [4, 5, 6]

预期结果:

>>> 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循环可以与元组变量一起工作,因此同时循环多个变量很简单。

其他回答

如果使用的是NumPy,可以使用以下命令连接两个兼容维度的数组:

numpy.concatenate([a,b])

您还可以使用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)

如果您需要使用复杂的排序规则合并两个有序列表,您可能需要像下面的代码一样自行滚动(使用简单的排序规则以提高可读性:-)。

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])

我推荐三种方法连接列表,但最推荐第一种方法,

# Easiest and least complexity method <= recommended

listone = [1, 2, 3]
listtwo = [4, 5, 6]

newlist = listone + listtwo
print(newlist)

# Second-easiest method
newlist = listone.copy()
newlist.extend(listtwo)
print(newlist)

在第二个方法中,我将newlist分配给listone的副本,因为我不想更改listone。

# Third method
newlist = listone.copy()
for j in listtwo:
    newlist.append(j)

print(newlist)

这不是连接列表的好方法,因为我们正在使用for循环来连接列表。所以时间复杂度比其他两种方法要高得多。