将列表元素插入列表列表的Pythonic方法?

Mar*_*ate 1 python list

比如说,让我们有:

nodes = [[1, 2],[3, 4]] 
thelist = [[5, 6], [7, 8]]
Run Code Online (Sandbox Code Playgroud)

我如何编码,所以列表将是:

[[1, 2],[3, 4],[5, 6],[7, 8]]
Run Code Online (Sandbox Code Playgroud)

我知道怎么做,但我想要一个优雅的蟒蛇方式.

我的尝试:

for node in nodes:
    thelist.insert(0, node)
Run Code Online (Sandbox Code Playgroud)

我想应该有更多的pythonic方式来做到这一点.

编辑:顺序不知何故很重要(这就是我尝试在索引0处插入的原因).

And*_*den 11

只需将它们加在一起:

In [11]: nodes + thelist
Out[11]: [[1, 2], [3, 4], [5, 6], [7, 8]]
Run Code Online (Sandbox Code Playgroud)

您还可以使用extend(修改节点):

In [12]: nodes.extend(thelist)

In [13]: nodes
Out[13]: [[1, 2], [3, 4], [5, 6], [7, 8]]
Run Code Online (Sandbox Code Playgroud)

  • +运算符返回一个新列表. (2认同)

flo*_*ake 8

您可以指定切片thelist[:0]以在开头插入元素:

nodes = [[1, 2],[3, 4]]
thelist = [[5, 6], [7, 8]]
thelist[:0] = nodes
# thelist is now [[1, 2], [3, 4], [5, 6], [7, 8]]
Run Code Online (Sandbox Code Playgroud)

有关操作列表的许多有用方法,请参阅Python教程.


Jon*_*nts 5

或者,如果某种顺序很重要,或者只是一次获取一个项目的能力,那么您可以使用heapq.merge:

import heapq

nodes = [[1, 2],[3, 4]]
thelist = [[5, 6], [7, 8]] 
res = list(heapq.merge(nodes, thelist))
# [[1, 2], [3, 4], [5, 6], [7, 8]]

nodes = [[1, 2], [5,6]]
thelist = [[3, 4], [7, 8]]    
res = list(heapq.merge(nodes, thelist))
# [[1, 2], [3, 4], [5, 6], [7, 8]]
Run Code Online (Sandbox Code Playgroud)

或者,只需使用:

for heapq.merge(nodes, thelist):
Run Code Online (Sandbox Code Playgroud)

请注意,订单可能不同于itertools.chain.