Python – manipulation of nested lists

Question:

let’s say I have a 3 nested lists. I would like to create a new nested lists so that the first nested list will contain first values from the prevoius 3 nested lists, the second nested list will contain second values from previous nested lists and so on. The example:

dd = [[5,8,3],[1,4,2],[1,2,3]]

dd = [[5,1,1],[8,4,2],[3,2,3]]
Asked By: Julian

||

Answers:

You can do this with zip,

In [1]: dd = [[5,8,3],[1,4,2],[1,2,3]]

In [2]: list(zip(*dd))
Out[2]: [(5, 1, 1), (8, 4, 2), (3, 2, 3)]

For a list of lists,

In [3]: list(map(list, zip(*dd)))
Out[3]: [[5, 1, 1], [8, 4, 2], [3, 2, 3]]
Answered By: Rahul K P

You tranpose the matrix like this.

dd = [[5,8,3],[1,4,2],[1,2,3]]

result = []

for i in range(len(dd)):
    temp = []
    for j in range(len(dd)):
        temp.append(dd[j][i])

    result.append(temp)

print(result)
Answered By: Asif
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.