I have a long list with nested lists with each list consisting of multiple xy-coordinates. In short, my lists looks like this
MyList = [ [ [1, 2], [1, 2] ], [ [1, 2], [1, 2] ], [ [1, 2], [1, 2] ]...]]]
I would like to extract all the "1's" to one variable, and all the "2's" to one variable. So extract first element to a new list, and extract second element to another new list. I have tried
for list in MyList:
for newList in list:
number1 = [item[0] for item in newList]
number2 = [item[1] for item in newList]
Which gave me the error "int object is not subscriptable". I also tried
def Extract(MyList):
return list(list(zip(*MyList))[0])
Lastly I tried to just print the "1's" out to see if it would work
print(MyList[:][:][0])
output: [[1, 2], [1, 2]]
CodePudding user response:
I would do it like so:
>>> a = MyList
>>> x = [a[i][j][0] for i in range(len(a)) for j in range(len(a[i]))]
>>> x
[1, 1, 1, 1, 1, 1]
>>> y = [a[i][j][1] for i in range(len(a)) for j in range(len(a[i]))]
>>> y
[2, 2, 2, 2, 2, 2]
You're basically iterating over each tuple of coordinates and take the X coordinate ([0]
), respectively the y coordinate ([1]
).
There might be better ways, this is the quick one I came up with.
CodePudding user response:
Try this:
flatlist = [el for lst1 in MyList for lst2 in lst1 for el in lst2]
number1, number2 = flatlist[0::2], flatlist[1::2]
First you flat the list, and then you split it into two lists with alternating elements.
CodePudding user response:
Simply you can handle this with three for loop if time complexity is not an issue:
one = []
two = []
for item in MyList:
for arr in item:
for num in arr:
if num == 1:
one.append(num)
else:
two.append(num)
# [1, 1, 1, 1, 1, 1]
# [2, 2, 2, 2, 2, 2]