简体   繁体   English

遍历嵌套列表中的列表 - Python

[英]Iterate through list in nested list - Python

I have a long list with nested lists with each list consisting of multiple xy-coordinates.我有一个带有嵌套列表的长列表,每个列表都包含多个 xy 坐标。 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.我想将所有“1”提取到一个变量,将所有“2”提取到一个变量。 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".这给了我错误“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最后,我尝试将“1”打印出来,看看它是否有效

print(MyList[:][:][0])
output: [[1, 2], [1, 2]]

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.首先将列表展平,然后将其拆分为两个具有交替元素的列表。

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] ).您基本上是在遍历每个坐标元组并分别获取 X 坐标( [0] )和 y 坐标( [1] )。

There might be better ways, this is the quick one I came up with.可能有更好的方法,这是我想出的快速方法。

Simply you can handle this with three for loop if time complexity is not an issue:如果时间复杂度不是问题,您只需使用三个 for 循环即可处理此问题:

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]  

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM