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]]
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]]
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)
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]]
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]]
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)