问题:如何在Python中串联两个列表?

如何在Python中串联两个列表?

例:

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

预期结果:

>>> joinedlist
[1, 2, 3, 4, 5, 6]

How do I concatenate two lists in Python?

Example:

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

Expected outcome:

>>> joinedlist
[1, 2, 3, 4, 5, 6]

回答 0

您可以使用+运算符来组合它们:

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

joinedlist = listone + listtwo

输出:

>>> joinedlist
[1,2,3,4,5,6]

You can use the + operator to combine them:

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

joinedlist = listone + listtwo

Output:

>>> joinedlist
[1,2,3,4,5,6]

回答 1

也可以创建一个生成器,使用来简单地遍历两个列表中的项目itertools.chain()。这使您可以将列表(或任何可迭代的)链接在一起进行处理,而无需将项目复制到新列表中:

import itertools
for item in itertools.chain(listone, listtwo):
    # Do something with each list item

It’s also possible to create a generator that simply iterates over the items in both lists using itertools.chain(). This allows you to chain lists (or any iterable) together for processing without copying the items to a new list:

import itertools
for item in itertools.chain(listone, listtwo):
    # Do something with each list item

回答 2

Python >= 3.5替代品:[*l1, *l2]

通过接受已经引入了另一种选择PEP 448,值得一提。

当在Python中使用加星标的表达式时,PEP的标题为Additional Unpacking Generalizations,通常会减少一些语法限制*。使用它,现在还可以使用以下方法来加入两个列表(适用于任何可迭代对象):

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> joined_list = [*l1, *l2]  # unpack both iterables in a list literal
>>> print(joined_list)
[1, 2, 3, 4, 5, 6]

此功能尚未回迁到该3.x系列的先前版本中。在不受支持的版本SyntaxError中,将被提出。

与其他方法一样,这也会在相应列表中创建元素的浅表副本


这种方法的好处是,您实际上不需要列表即可执行它,任何可迭代的操作都可以。如PEP中所述:

这对于将可迭代项求和成一个列表(如my_list + list(my_tuple) + list(my_range)现在等同于just)的可读性更高,也很有用[*my_list, *my_tuple, *my_range]

因此,虽然加上+与会TypeError由于类型不匹配而引发:

l = [1, 2, 3]
r = range(4, 7)
res = l + r

以下内容不会:

res = [*l, *r]

因为它首先将可迭代对象的内容解包,然后list仅从内容中创建一个即可。

Python >= 3.5 alternative: [*l1, *l2]

Another alternative has been introduced via the acceptance of PEP 448 which deserves mentioning.

The PEP, titled Additional Unpacking Generalizations, generally reduced some syntactic restrictions when using the starred * expression in Python; with it, joining two lists (applies to any iterable) can now also be done with:

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]
>>> joined_list = [*l1, *l2]  # unpack both iterables in a list literal
>>> print(joined_list)
[1, 2, 3, 4, 5, 6]

This functionality it hasn’t been backported to previous versions in the 3.x family. In unsupported versions a SyntaxError is going to be raised.

As with the other approaches, this too creates as shallow copy of the elements in the corresponding lists.


The upside to this approach is that you really don’t need lists in order to perform it, anything that is iterable will do. As stated in the PEP:

This is also useful as a more readable way of summing iterables into a list, such as my_list + list(my_tuple) + list(my_range) which is now equivalent to just [*my_list, *my_tuple, *my_range].

So while addition with + would raise a TypeError due to type mismatch:

l = [1, 2, 3]
r = range(4, 7)
res = l + r

The following won’t:

res = [*l, *r]

because it will first unpack the contents of the iterables and then simply create a list from the contents.


回答 3

您可以使用集合来获取唯一值的合并列表

mergedlist = list(set(listone + listtwo))

You can use sets to obtain merged list of unique values

mergedlist = list(set(listone + listtwo))

回答 4

您也可以使用方法将a添加list到另一个的结尾:

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

listone.extend(listtwo)

如果要保持原始列表完整无缺,则可以创建一个新list对象,并且extend两个列表都指向该对象:

mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)

You could also use the method in order to add a list to the end of another one:

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

listone.extend(listtwo)

If you want to keep the original list intact, you can create a new list object, and extend both lists to it:

mergedlist = []
mergedlist.extend(listone)
mergedlist.extend(listtwo)

回答 5

如何在Python中串联两个列表?

从3.7开始,这些是在python中串联两个(或多个)列表的最受欢迎的stdlib方法。

在此处输入图片说明

脚注

  1. 由于它的简洁性,这是一个不错的解决方案。但是sum以成对方式执行串联操作,这意味着这是二次操作,因为必须为每个步骤分配内存。如果您的列表很大,请不要使用。

  2. 查看 和阅读 文档。您需要import itertools先。串联在内存中是线性的,因此这在性能和版本兼容性方面是最佳的。chain.from_iterable在2.6中引入。

  3. 此方法使用“ 其他解包概述”(PEP 448),但除非您手动手动解压缩每个列表,否则无法将其归纳为N个列表。

  4. a += ba.extend(b)在所有实际用途上大致相同。+=当在列表上调用时list.__iadd__,将内部调用 ,从而将第一个列表扩展到第二个列表。


性能

2列表串联1

在此处输入图片说明

这些方法之间没有太大区别,但是鉴于它们都具有相同的复杂度顺序(线性),这是有道理的。除了风格之外,没有特别的理由比一个更喜欢一个。

N列表串联

在此处输入图片说明

使用perfplot模块已生成图。代码,供您参考。

1. iadd+=)和extend方法就地操作,因此每次测试前都必须生成一个副本。为了公平起见,所有方法在左侧列表中都有一个预复制步骤,可以忽略。


对其他解决方案的评论

  • 请勿list.__add__以任何方式,形状或形式直接使用DUNDER方法。实际上,请避免使用dunder方法,并使用operator设计用于它们的运算符和函数。Python具有仔细的语义,这些语义比直接调用dunder更复杂。这是一个例子。因此,总而言之,a.__add__(b)=>差;a + b=>好。

  • 此处提供reduce(operator.add, [a, b])了成对连接的一些答案-这与sum([a, b], [])更多单词一样。

  • 使用的任何方法都set将删除重复项并失去顺序。请谨慎使用。

  • for i in b: a.append(i)a.extend(b)单一功能调用和惯用语言更加罗word,并且速度更慢。append之所以变慢,是因为为列表分配和增长了内存的语义。参见此处进行类似的讨论。

  • heapq.merge可以使用,但是它的用例是在线性时间内合并排序列表。在任何其他情况下使用它都是一种反模式。

  • yield从函数中列出列表元素是一种可以接受的方法,但是chain这样做更快,更好(它在C中具有代码路径,因此速度很快)。

  • operator.add(a, b)是可以接受的等效功能a + b。它的用例主要用于动态方法分派。否则,在我看来,最好选择更a + b短,更易读的格式。YMMV。

How do I concatenate two lists in Python?

As of 3.7, these are the most popular stdlib methods for concatenating two (or more) lists in python.

enter image description here

Footnotes

  1. This is a slick solution because of its succinctness. But sum performs concatenation in a pairwise fashion, which means this is a quadratic operation as memory has to be allocated for each step. DO NOT USE if your lists are large.

  2. See and from the docs. You will need to import itertools first. Concatenation is linear in memory, so this is the best in terms of performance and version compatibility. chain.from_iterable was introduced in 2.6.

  3. This method uses Additional Unpacking Generalizations (PEP 448), but cannot generalize to N lists unless you manually unpack each one yourself.

  4. a += b and a.extend(b) are more or less equivalent for all practical purposes. += when called on a list will internally call list.__iadd__, which extends the first list by the second.


Performance

2-List Concatenation1

enter image description here

There’s not much difference between these methods but that makes sense given they all have the same order of complexity (linear). There’s no particular reason to prefer one over the other except as a matter of style.

N-List Concatenation

enter image description here

Plots have been generated using the perfplot module. Code, for your reference.

1. The iadd (+=) and extend methods operate in-place, so a copy has to be generated each time before testing. To keep things fair, all methods have a pre-copy step for the left-hand list which can be ignored.


Comments on Other Solutions

  • DO NOT USE THE DUNDER METHOD list.__add__ directly in any way, shape or form. In fact, stay clear of dunder methods, and use the operators and operator functions like they were designed for. Python has careful semantics baked into these which are more complicated than just calling the dunder directly. Here is an example. So, to summarise, a.__add__(b) => BAD; a + b => GOOD.

  • Some answers here offer reduce(operator.add, [a, b]) for pairwise concatenation — this is the same as sum([a, b], []) only more wordy.

  • Any method that uses set will drop duplicates and lose ordering. Use with caution.

  • for i in b: a.append(i) is more wordy, and slower than a.extend(b), which is single function call and more idiomatic. append is slower because of the semantics with which memory is allocated and grown for lists. See here for a similar discussion.

  • heapq.merge will work, but its use case is for merging sorted lists in linear time. Using it in any other situation is an anti-pattern.

  • yielding list elements from a function is an acceptable method, but chain does this faster and better (it has a code path in C, so it is fast).

  • operator.add(a, b) is an acceptable functional equivalent to a + b. It’s use cases are mainly for dynamic method dispatch. Otherwise, prefer a + b which is shorter and more readable, in my opinion. YMMV.


回答 6

这很简单,我认为它甚至在本教程中已显示:

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

This is quite simple, and I think it was even shown in the tutorial:

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

回答 7

这个问题直接询问有关加入两个列表的问题。但是,即使您正在寻找加入许多列表的方式(包括加入零列表的情况),其搜索量也很高。

我认为最好的选择是使用列表推导:

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

请注意,这在ais []或时也可以正常使用[[1,2,3]]

但是,可以使用以下命令更有效地完成此操作itertools

a = [[1,2,3], [4,5,6], [7,8,9]]
list(itertools.chain(*a))

如果不需要a list,而只是需要迭代,请省略list()

更新资料

Patrick Collins在评论中建议的替代方法也可能对您有用:

sum(a, [])

This question directly asks about joining two lists. However it’s pretty high in search even when you are looking for a way of joining many lists (including the case when you joining zero lists).

I think the best option is to use list comprehensions:

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

You can create generators as well:

>>> map(str, (x for xs in a for x in xs))
['1', '2', '3', '4', '5', '6', '7', '8', '9']

Old Answer

Consider this more generic approach:

a = [[1,2,3], [4,5,6], [7,8,9]]
reduce(lambda c, x: c + x, a, [])

Will output:

[1, 2, 3, 4, 5, 6, 7, 8, 9]

Note, this also works correctly when a is [] or [[1,2,3]].

However, this can be done more efficiently with itertools:

a = [[1,2,3], [4,5,6], [7,8,9]]
list(itertools.chain(*a))

If you don’t need a list, but just an iterable, omit list().

Update

Alternative suggested by Patrick Collins in the comments could also work for you:

sum(a, [])

回答 8

您可以简单地使用+or +=运算符,如下所示:

a = [1, 2, 3]
b = [4, 5, 6]

c = a + b

要么:

c = []
a = [1, 2, 3]
b = [4, 5, 6]

c += (a + b)

另外,如果您希望合并列表中的值唯一,则可以执行以下操作:

c = list(set(a + b))

You could simply use the + or += operator as follows:

a = [1, 2, 3]
b = [4, 5, 6]

c = a + b

Or:

c = []
a = [1, 2, 3]
b = [4, 5, 6]

c += (a + b)

Also, if you want the values in the merged list to be unique you can do:

c = list(set(a + b))

回答 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_iterable则可以使用class方法:

>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']

It’s worth noting that the itertools.chain function accepts variable number of arguments:

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

If an iterable (tuple, list, generator, etc.) is the input, the from_iterable class method may be used:

>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']

回答 10

使用Python 3.3+,您可以使用yield from

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]

With Python 3.3+ you can use yield from:

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]

Or, if you want to support an arbitrary number of iterators:

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]

回答 11

如果你想在排序的形式两个列表合并,您可以使用merge从函数heapq库。

from heapq import merge

a = [1, 2, 4]
b = [2, 4, 6, 7]

print list(merge(a, b))

If you want to merge the two lists in sorted form, you can use the merge function from the heapq library.

from heapq import merge

a = [1, 2, 4]
b = [2, 4, 6, 7]

print list(merge(a, b))

回答 12

如果您不能使用加号(+),则可以使用operator导入:

import operator

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

result = operator.add(listone, listtwo)
print(result)

>>> [1, 2, 3, 4, 5, 6]

另外,您也可以使用__add__ dunder函数:

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

result = list.__add__(listone, listtwo)
print(result)

>>> [1, 2, 3, 4, 5, 6]

If you can’t use the plus operator (+), you can use the operator import:

import operator

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

result = operator.add(listone, listtwo)
print(result)

>>> [1, 2, 3, 4, 5, 6]

Alternatively, you could also use the __add__ dunder function:

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

result = list.__add__(listone, listtwo)
print(result)

>>> [1, 2, 3, 4, 5, 6]

回答 13

作为更多列表的更通用方法,您可以将它们放在列表中并使用itertools.chain.from_iterable()1函数,该函数基于答案是扁平化嵌套列表的最佳方法:

>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

1.请注意,这chain.from_iterable()在Python 2.6和更高版本中可用。在其他版本中,请使用chain(*l)

As a more general way for more lists you can put them within a list and use the itertools.chain.from_iterable()1 function which based on this answer is the best way for flatting a nested list:

>>> l=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> import itertools
>>> list(itertools.chain.from_iterable(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]

1. Note that chain.from_iterable() is available in Python 2.6 and later. In other versions, use chain(*l).


回答 14

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

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

If you need to merge two ordered lists with complicated sorting rules, you might have to roll it yourself like in the following code (using a simple sorting rule for readability :-) ).

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

回答 15

您可以使用append()list对象上定义的方法:

mergedlist =[]
for elem in listone:
    mergedlist.append(elem)
for elem in listtwo:
    mergedlist.append(elem)

You could use the append() method defined on list objects:

mergedlist =[]
for elem in listone:
    mergedlist.append(elem)
for elem in listtwo:
    mergedlist.append(elem)

回答 16

list(set(listone) | set(listtwo))

上面的代码不保留顺序,而是从每个列表中删除重复项(但不从串联列表中删除)

list(set(listone) | set(listtwo))

The above code, does not preserve order, removes duplicate from each list (but not from the concatenated list)


回答 17

正如许多人已经指出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
        [...]

这里要理解的要点是,列表只是可迭代的特例,它们是与其他对象一样的对象。并且for ... inpython 中的循环可以使用元组变量,因此同时循环多个变量很简单。

As already pointed out by many, itertools.chain() is the way to go if one needs to apply exactly the same treatment to both lists. In my case, I had a label and a flag which were different from one list to the other, so I needed something slightly more complex. As it turns out, behind the scenes itertools.chain() simply does the following:

for it in iterables:
    for element in it:
        yield element

(see https://docs.python.org/2/library/itertools.html), so I took inspiration from here and wrote something along these lines:

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
        [...]

The main points to understand here are that lists are just a special case of iterable, which are objects like any other; and that for ... in loops in python can work with tuple variables, so it is simple to loop on multiple variables at the same time.


回答 18

使用简单的列表理解:

joined_list = [item for list_ in [list_one, list_two] for item in list_]

它具有使用附加解包概括的最新方法的所有优点-即您可以以这种方式连接任意数量的不同可迭代对象(例如,列表,元组,范围和生成器)-而且不限于Python 3.5或更高版本。

Use a simple list comprehension:

joined_list = [item for list_ in [list_one, list_two] for item in list_]

It has all the advantages of the newest approach of using Additional Unpacking Generalizations – i.e. you can concatenate an arbitrary number of different iterables (for example, lists, tuples, ranges, and generators) that way – and it’s not limited to Python 3.5 or later.


回答 19

合并列表列表的一种非常简洁的方法是

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]

A really concise way to combine a list of lists is

list_of_lists = [[1,2,3], [4,5,6], [7,8,9]]
reduce(list.__add__, list_of_lists)

which gives us

[1, 2, 3, 4, 5, 6, 7, 8, 9]

回答 20

在Python中,您可以使用此命令来连接两个兼容维度的数组

numpy.concatenate([a,b])

In Python you can concatenate two arrays of compatible dimensions with this command

numpy.concatenate([a,b])

回答 21

因此,有两种简单的方法。

  1. 使用+:它从提供的列表中创建一个新列表

例:

In [1]: a = [1, 2, 3]

In [2]: b = [4, 5, 6]

In [3]: a + b
Out[3]: [1, 2, 3, 4, 5, 6]

In [4]: %timeit a + b
10000000 loops, best of 3: 126 ns per loop
  1. 使用extend:将新列表追加到现有列表。这意味着它不会创建单独的列表。

例:

In [1]: a = [1, 2, 3]

In [2]: b = [4, 5, 6]

In [3]: %timeit a.extend(b)
10000000 loops, best of 3: 91.1 ns per loop

因此,我们看到在两种最流行的方法中,它extend是有效的。

So there are two easy ways.

  1. Using +: It creates a new list from provided lists

Example:

In [1]: a = [1, 2, 3]

In [2]: b = [4, 5, 6]

In [3]: a + b
Out[3]: [1, 2, 3, 4, 5, 6]

In [4]: %timeit a + b
10000000 loops, best of 3: 126 ns per loop
  1. Using extend: It appends new list to existing list. That means it does not create a separate list.

Example:

In [1]: a = [1, 2, 3]

In [2]: b = [4, 5, 6]

In [3]: %timeit a.extend(b)
10000000 loops, best of 3: 91.1 ns per loop

Thus we see that out of two of most popular methods, extend is efficient.


回答 22

有多种方法可以在python中串联列表。

l1 = [1,2,3,4]
l2 = [3,4,5,6]

1. new_list = l1.extend(l2)
2. new_list = l1 + l2
3. new_list = [*l1, *l2]

There are multiple ways to concatenete lists in python.

l1 = [1,2,3,4]
l2 = [3,4,5,6]

1. new_list = l1.extend(l2)
2. new_list = l1 + l2
3. new_list = [*l1, *l2]

回答 23

import itertools

A = list(zip([1,3,5,7,9],[2,4,6,8,10]))
B = [1,3,5,7,9]+[2,4,6,8,10]
C = list(set([1,3,5,7,9] + [2,4,6,8,10]))

D = [1,3,5,7,9]
D.append([2,4,6,8,10])

E = [1,3,5,7,9]
E.extend([2,4,6,8,10])

F = []
for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):
    F.append(a)


print ("A: " + str(A))
print ("B: " + str(B))
print ("C: " + str(C))
print ("D: " + str(D))
print ("E: " + str(E))
print ("F: " + str(F))

输出:

A: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
C: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
import itertools

A = list(zip([1,3,5,7,9],[2,4,6,8,10]))
B = [1,3,5,7,9]+[2,4,6,8,10]
C = list(set([1,3,5,7,9] + [2,4,6,8,10]))

D = [1,3,5,7,9]
D.append([2,4,6,8,10])

E = [1,3,5,7,9]
E.extend([2,4,6,8,10])

F = []
for a in itertools.chain([1,3,5,7,9], [2,4,6,8,10]):
    F.append(a)


print ("A: " + str(A))
print ("B: " + str(B))
print ("C: " + str(C))
print ("D: " + str(D))
print ("E: " + str(E))
print ("F: " + str(F))

Output:

A: [(1, 2), (3, 4), (5, 6), (7, 8), (9, 10)]
B: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
C: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
D: [1, 3, 5, 7, 9, [2, 4, 6, 8, 10]]
E: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
F: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]

回答 24

如果您想要一个新列表,同时保留两个旧列表:

def concatenate_list(listOne, listTwo):
    joinedList = []
    for i in listOne:
        joinedList.append(i)
    for j in listTwo:
        joinedList.append(j)

    sorted(joinedList)

    return joinedList

If you wanted a new list whilst keeping the two old lists:

def concatenate_list(listOne, listTwo):
    joinedList = []
    for i in listOne:
        joinedList.append(i)
    for j in listTwo:
        joinedList.append(j)

    sorted(joinedList)

    return joinedList

回答 25

lst1 = [1,2]

lst2 = [3,4]

def list_combinationer(Bushisms, are_funny):

    for item in lst1:
        lst2.append(item)
        lst1n2 = sorted(lst2)
        print lst1n2

list_combinationer(lst1, lst2)

[1,2,3,4]
lst1 = [1,2]

lst2 = [3,4]

def list_combinationer(Bushisms, are_funny):

    for item in lst1:
        lst2.append(item)
        lst1n2 = sorted(lst2)
        print lst1n2

list_combinationer(lst1, lst2)

[1,2,3,4]

回答 26

您可以按照代码进行操作

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

for i in listone:
    listtwo.append(i)
print(listtwo)

[1,2,3,4,5,6]

You may follow the code

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

for i in listone:
    listtwo.append(i)
print(listtwo)

[1,2,3,4,5,6]

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。