I want to convert a 3D list (list_1) into a 2D list (list_2). For example:
list_1: [[[3], [4]], [[5], [6]], [[7], [8]]]
list_2: [[3, 4], [5, 6], [7, 8]]
This is what I have already tried:
[e for sl in lst for e in sl]
But the result would be different:
[[3], [4], [5], [6], [7], [8]]
For readibility I'd suggest itertools.chain
to flatten the inner lists here:
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]]
Following your approach, you'd need an extra level of looping to flatten the inner lists:
[[i for e in sl for i in e] for sl in l]
# [[3, 4], [5, 6], [7, 8]]
另外一个选项:
[reduce(list.__add__, x) for x in list_1]
you can also do it like this:
l = [[[3], [4]], [[5], [6]], [[7], [8]]]
print ([sum(item, []) for item in l])
output:
[[3, 4], [5, 6], [7, 8]]
您接近:
[[c for b in a for c in b] for a in lst]
If all your nested lists contain single elements, you can use unpacking:
d = [[[3], [4]], [[5], [6]], [[7], [8]]]
new_d = [[i for [i] in b] for b in d]
Output:
[[3, 4], [5, 6], [7, 8]]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.