python - 迭代 python 嵌套列表

标签 python list nested nested-lists

我需要将列表 'a' 转换为列表 'b' , 怎么做?

a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]

b = [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12,]]]

最佳答案

我建议以下列表理解:

In [1]: a = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12,]]]
   ...:

In [2]: [[[a for sub in nested for a in sub]] for nested in a]
Out[2]: [[[1, 2, 3, 4, 5, 6]], [[7, 8, 9, 10, 11, 12]]]

它等价于下面的嵌套for循环:

result = []
for nested in a:
    _temp = []
    for sub in nested:
        for a in sub:
            _temp.append(a)
    result.append([_temp])

不过,我更愿意这样写:

result = []
for nested in a:
    _temp = []
    for sub in nested:
        _temp.extend(sub)
    result.append([_temp])

关于python - 迭代 python 嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51918244/

相关文章:

python - 为 Python 设置 Vim

c++ - 如何将 list<T> 对象附加到另一个对象

c++ - 使用嵌套的 if 语句来构造代码

jquery - 如何在不破坏每个 <ul> 位置的情况下向嵌套 <ul> 列表中的每个 <ul> 添加滚动条

python - 如何根据键值和嵌套值编辑嵌套字典中的值

python - 新手在 Python 中遇到简单的 "while"重复

python - 如何在 Python 中编码 JWT?

python - 从 pony ORM 创建 postgres 数据库

list - 在 Go 列表中按值删除元素

Android 保存列表<String>