循环遍历Python中的列表列表

时间:2017-02-26 13:50:11

标签: python arrays

我有一个包含其他列表的列表:

self.trails = [
  [10, 50],
  [20, 30],
  [100,50],
  [25, 75]
]

我正试图遍历它并删除任何项目,如果它们距离其他坐标太近了:

def distance_real(x1,y1,x2,y2):
    return Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) )

class MathClass
   trails = [
      [10, 50],
      [20, 30],
      [100,50],
      [25, 75]
   ]

   def run(self):
      pointx = 10
      pointy = 15

      while 1:
         for trail in self.trails:
             d = distance_real(pointx, pointy, trail[0], trail[1])
                 if d < 5:
                    self.trails.remove(trail)
         time.sleep( 1.0/30 )

代码不会删除所有应该删除的路径。添加for循环并将其循环五次后,它成功删除了它们。

有什么想法吗?在我的情况下使用for循环效率不高,因为trail包含几千个实体,代码必须在几毫秒内运行。

2 个答案:

答案 0 :(得分:2)

首先在tmp列表上执行操作,然后在结尾处为trails分配

def distance_real(x1,y1,x2,y2):
    return Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) )

class MathClass
   trails = [
      [10, 50],
      [20, 30],
      [100,50],
      [25, 75]
   ]

   def run(self):
       pointx = 10
       pointy = 15

       tmp = []
       while 1:
           for trail in self.trails:
               d = distance_real(pointx, pointy, trail[0], trail[1])
               if d >= 5:
                   tmp.append(trail)
           self.trails = tmp
           time.sleep( 1.0/30 )

答案 1 :(得分:1)

您在迭代时修改列表。尝试将其转换为元组,如下所示:

for trail in tuple(self.trails):
    d = distance_real(pointx, pointy, trail[0], trail[1])
    if d < 5:
        self.trails.remove(trail)

或一行:

self.trails = [
    x for x in self.trails if
    distance_real(pointx, pointy, trail[0], trail[1]) >= 5]