I’m trying to turn a nested list of lists (number of lists can be 2 lists +) into a single list of tuples.
The list looks something like this:
JavaScript
x
2
1
exampleList = [['A', 'B', 'C', 'D'], [1, 2, 3, 4], [10, 20, 30, 40]]
2
And I would like for it to be like this:
JavaScript
1
2
1
newList = [('A', 1, 10), ('B', 2, 20), ('C', 3, '30)...]
2
I know that if you do zip(list1, list2)
, it becomes a list of tuple. But how do I go about doing it for a list of lists?
I tried using the zip
concept with:
JavaScript
1
4
1
test = []
2
for data in exampleList:
3
test.append(zip(data))
4
But it did not work out for me.
Advertisement
Answer
JavaScript
1
4
1
>>> exampleList = [['A', 'B', 'C', 'D'], [1, 2, 3, 4], [10, 20, 30, 40]]
2
>>> list(zip(*exampleList))
3
[('A', 1, 10), ('B', 2, 20), ('C', 3, 30), ('D', 4, 40)]
4
Edit:
If you want your output to be a list of lists, instead of a list of tuples,
JavaScript
1
2
1
[list(i) for i in zip(*empampleList)]
2
should do the trick