我需要将列表 '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/