简体   繁体   中英

List of lists of lists in Python

I am trying to convert a list Ii02 into a list of lists as shown in the expected output.

Ii02 = [[[0, 1], [0, 2], [1, 3], [4, 3], [2, 4]], [[0, 1], [0, 2], [1, 3], [4, 3], [3, 4], [2, 5]]]
for h in range(0,len(Ii02)):
    Ii03=[[[i] for i in Ii02[h]]]
    print(Ii03)

The current output is

[[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[3, 4]], [[2, 5]]]]

The expected output is

[[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[2, 4]]],
[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[3, 4]], [[2, 5]]]]

You can do that with a nested list comprehension:

[[[j] for j in i] for i in Ii02]

Output:

[[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[2, 4]]], 
[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[3, 4]], [[2, 5]]]]

Here we go. The code is quite simple and self-explanatory.

Ii02 = [[[0, 1], [0, 2], [1, 3], [4, 3], [2, 4]], [[0, 1], [0, 2], [1, 3], [4, 3], [3, 4], [2, 5]]]
Ii03 = []
for h in range(0,len(Ii02)):
    Ii03.append([[i] for i in Ii02[h]])
print(Ii03)

Output

[[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[2, 4]]], [[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[3, 4]], [[2, 5]]]]

The code is simple.

Ii02 = [[[0, 1], [0, 2], [1, 3], [4, 3], [2, 4]], [[0, 1], [0, 2], [1, 3], [4, 3], [3, 4], [2, 5]]]
Ii03 = []

for h in Ii02:
    Ii03.append([[i] for i in h])
print(Ii03)

Output is:

[[[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[2, 4]]], [[[0, 1]], [[0, 2]], [[1, 3]], [[4, 3]], [[3, 4]], [[2, 5]]]]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM