List of lists of lists in Python

Question:

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]]]]
Asked By: Klimt865

||

Answers:

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]]]]
Answered By: Nin17

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]]]]
Answered By: Prateek

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]]]]
Answered By: pradipghevaria
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.