【问题标题】:Multiple List duplication removal in for loopsfor循环中的多个列表重复删除
【发布时间】:2018-05-21 10:30:42
【问题描述】:

我有一个函数必须同时检查两个列表中的重复项。对于笛卡尔系统,一个列表具有 x 值,另一个具有 y 值。单个坐标不能重复。目前我的代码如下所示:

    for q in range(0, len(prows)-1, 1):
            for w in range(0, len(prows)-1, 1):
                if prows[q] == prows[w] and pcols[q] == prows[w]:
                    prows.remove(prows[w])
                    pcols.remove(pcols[w])

prows 是 y 值,pcols 是 x 值。这行得通,问题是我的第一个 for 循环仅在第二个 for 循环遍历其所有值之后更新 prows 的长度。因此,我得到一个索引错误,第一个 for 循环仍然具有原始长度,而第二个 for 循环具有较新的长度并删除了重复。

【问题讨论】:

    标签: python list loops indexing


    【解决方案1】:

    利用 dicts 保留其键的插入顺序这一事实(在 Python 3.7 中为 will become part of the specification,但在 3.6 中已经如此),这可以在一行中完成:

    # create some data       
    >>> import random
    >>> a = [random.randint(0, 3) for _ in range(20)]
    >>> b = [random.randint(0, 3) for _ in range(20)]
    >>> 
    >>> a
    [0, 3, 2, 1, 2, 0, 1, 2, 0, 2, 1, 1, 0, 3, 1, 3, 1, 2, 3, 2]
    >>> b
    [1, 0, 3, 2, 2, 2, 2, 3, 1, 2, 1, 1, 1, 1, 3, 0, 0, 0, 3, 3]
    >>> 
    # this one line is all we need
    >>> au, bu = zip(*dict.fromkeys(zip(a, b)))
    >>> 
    # admire
    >>> au
    (0, 3, 2, 1, 2, 0, 1, 3, 1, 1, 2, 3)
    >>> bu
    (1, 0, 3, 2, 2, 2, 1, 1, 3, 0, 0, 3)
    

    请注意,与人们预期的相反,这不适用于集合 --- 确实必须使用 dict(带有虚拟值)。

    【讨论】:

      【解决方案2】:
      xlist = [ 1, 3, 5, 7, 9, 5]
      ylist = [11,33,55,77,99,55]   # (5,55) dupe'd
      
      coords = list(zip(xlist,ylist)) # list of unique coords
      
      print(coords) # still has dupes
      
      result = []       # empty result list, no dupes allowed
      setCoords = set() # remember which coords we already put into result
      for c in coords:  # go through original coords, one at a time
          if c in setCoords:  # we already added this, skip it
              continue
          setCoords.add(c)    # add to set for comparison
          result.append(c)    # add to result
      
      print(result) # no dupes, still in order of list
      

      输出:

      [(1, 11), (3, 33), (5, 55), (7, 77), (9, 99), (5, 55)] # coords, with dupes
      [(1, 11), (3, 33), (5, 55), (7, 77), (9, 99)]          # result, no dupes
      

      你也可以恢复到 xlist 和 ylist 做:

      x2 , y2 = [list(tups) for tups in zip(*result)]
      
      print(x2)
      print(y2)
      

      输出:

      [1, 3, 5, 7, 9] 
      [11, 33, 55, 77, 99]
      

      【讨论】:

        猜你喜欢
        • 2017-04-17
        • 1970-01-01
        • 2021-10-12
        • 2013-09-26
        • 1970-01-01
        • 2011-07-21
        • 1970-01-01
        • 2021-06-21
        • 2019-03-14
        相关资源
        最近更新 更多