【问题标题】:Search for duplicates of items in list within list在列表中搜索列表中的重复项
【发布时间】:2019-10-22 14:06:33
【问题描述】:

从事一个基本项目,使用 matplotlib 模拟有机体的生命周期。有机体的位置由列表 [x,y] 定义,其位置是随机生成的。有机体是类

    for i in range(numorganisms):
        posX = random.randint(0,XMAX)
        posY = random.randint(0,YMAX)
        creatures.append(organism([posX,posY]))

情节中可能有大约 100 个,这意味着会发生碰撞。我希望能够在生物列表中搜索 posX 和 posY 都相等的实例,然后创建这些位置的新列表。

【问题讨论】:

    标签: python list search duplicates output


    【解决方案1】:

    您可以轻松做到这一点:

    existing = set()
    for i in range(numorganisms):
        posX = random.randint(0,XMAX)
        posY = random.randint(0,YMAX)
        if (posX, posY) not in existing :
            creatures.append(organism([posX,posY]))
            existing.add( (posX, posY) )
        else :
            pass   # do something else
    

    【讨论】:

      【解决方案2】:

      这假设您有一些方法可以从organism 的实例中获取位置。

      ###############################
      # This just recreates what I think you already have
      import random
      class organism:
          def __init__(self, l):
              self.l = l
      
      XMAX = YMAX = 100
      creatures = []
      for i in range(100):
          posX = random.randint(0,XMAX)
          posY = random.randint(0,YMAX)
          creatures.append(organism([posX,posY]))
      print(creatures)
      ###############################
      
      # Determine if there are redundancies
      positions = [x.l for x in creatures]
      print(positions)
      collisions = [i for i in positions if positions.count(i) > 1]
      print(collisions)
      

      【讨论】:

        猜你喜欢
        • 2014-04-21
        • 2020-04-05
        • 2013-01-30
        • 1970-01-01
        • 2015-08-28
        • 2019-05-25
        • 2012-05-22
        • 1970-01-01
        • 2014-12-14
        相关资源
        最近更新 更多