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

标签 python list

<分区>

让我们举个例子:

nodes = [[1, 2],[3, 4]] 
thelist = [[5, 6], [7, 8]]

如何编写代码以便列表为:

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

我知道怎么做,但我想要一种优雅的 python 方式。

我的尝试:

for node in nodes:
    thelist.insert(0, node)

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

编辑:顺序在某种程度上很重要(这就是我尝试在索引 0 处插入的原因)。

最佳答案

简单地将它们加在一起:

In [11]: nodes + thelist
Out[11]: [[1, 2], [3, 4], [5, 6], [7, 8]]

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

In [12]: nodes.extend(thelist)

In [13]: nodes
Out[13]: [[1, 2], [3, 4], [5, 6], [7, 8]]

关于python - 将列表元素插入列表列表的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18663571/

相关文章:

python - 通过 pyCharm windows 8 安装 scipy 时遇到问题 - 找不到 lapack/blas 资源

Python SSL套接字无法连接到自签名证书

python - 在不导入任何模块的情况下以 min :sec, 格式对时间进行排序的有效方法是什么?

python - 尝试比较列表元素

python - 列表理解输出

python - 如何获取元素在列表中出现的次数 Python

python - 如何将此项目 append 到同一列表中,而不是每次循环时创建一个新列表?

python - 为什么 pygame.MOUSEBUTTONDOWN 永远不等于我的按钮,即使用户单击它?

python - 使用 BeautifulSoup 选择特定的 <tr> 标签

python - 在 Python 中管道标准输出时设置正确的编码