Say I have multiple lists of lists. Something like this:
list1 = [[1,2],[56,32],[34,244]]
list2 = [[43,21],[30,1],[19,3]]
list3 = [[1,3],[8,21],[9,57]]
I want to create two new lists:
right_side = [2,32,244,21,1,3,3,21,57]
left_side = [1,56,34,43,30,19,1,8,9]
All sub-lists have only two values. And all big lists (list1,list2,list3) have the same number of values as well.
How do I do that?
CodePudding user response:
By using zip built-in function you get tuples:
left_side, right_side = zip(*list1, *list2, *list3)
And if you really need lists:
left_side, right_side = map(list, zip(*list1, *list2, *list3))
CodePudding user response:
The below seems to work.
list1 = [[1, 2], [56, 32], [34, 244]]
list2 = [[43, 21], [30, 1], [19, 3]]
list3 = [[1, 3], [8, 21], [9, 57]]
left = []
right = []
lst = [list1, list2, list3]
for l in lst:
for ll in l:
left.append(ll[0])
right.append(ll[1])
print(f'Left: {left}')
print(f'Right: {right}')
CodePudding user response:
If you do not have any issues with importing some standard libraries, you might achieve the goal as follows:
import itertools
from operator import itemgetter
right_side = list(map(itemgetter(1), itertools.chain(list1, list2, list3)))
left_side = list(map(itemgetter(0), itertools.chain(list1, list2, list3)))
Output of the due print
s shall be:
[2, 32, 244, 21, 1, 3, 3, 21, 57]
[1, 56, 34, 43, 30, 19, 1, 8, 9]
CodePudding user response:
You can use numpy
import numpy as np
All = list1 list2 list3
All = np.array(All)
print(All[:,1].tolist())
Gives right elemnst #
[2, 32, 244, 21, 1, 3, 3, 21, 57]
To get left #
print(All[:,0].tolist())
Gives #
[1, 56, 34, 43, 30, 19, 1, 8, 9]
>>>