我想将3D列表(列表_1)转换为2D列表(列表_2)。 例如:
list_1: [[[3], [4]], [[5], [6]], [[7], [8]]]
list_2: [[3, 4], [5, 6], [7, 8]]
这是我已经尝试过的:
[e for sl in lst for e in sl]
但是结果会有所不同:
[[3], [4], [5], [6], [7], [8]]
答案 0 :(得分:2)
出于可读性考虑,我建议itertools.chain
将此处的内部列表展平:
from itertools import chain
l = [[[3], [4]], [[5], [6]], [[7], [8]]]
[list(chain.from_iterable(i)) for i in l]
# [[3, 4], [5, 6], [7, 8]]
按照您的方法,您需要进行额外的循环以平化内部列表:
[[i for e in sl for i in e] for sl in l]
# [[3, 4], [5, 6], [7, 8]]
答案 1 :(得分:0)
另一个选择:
[reduce(list.__add__, x) for x in list_1]
答案 2 :(得分:0)
您也可以这样:
l = [[[3], [4]], [[5], [6]], [[7], [8]]]
print ([sum(item, []) for item in l])
输出:
[[3, 4], [5, 6], [7, 8]]
答案 3 :(得分:0)
您很亲密:
[[c for b in a for c in b] for a in lst]
答案 4 :(得分:0)
如果所有嵌套列表都包含单个元素,则可以使用拆包:
d = [[[3], [4]], [[5], [6]], [[7], [8]]]
new_d = [[i for [i] in b] for b in d]
输出:
[[3, 4], [5, 6], [7, 8]]