【问题标题】:Remove duplicates and original from list从列表中删除重复项和原始项
【发布时间】:2015-01-03 14:38:42
【问题描述】:

给定一个字符串列表,我想删除重复的单词和原始单词。

例如:

lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']

输出应删除重复项, 所以像这样['a', 'b', 'd']

我不需要保留订单。

【问题讨论】:

    标签: python list duplicates


    【解决方案1】:

    您可以创建一个辅助空列表,并且只附加尚未包含在其中的项目。

    oldList = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
    newList = []
    for item in oldList:
        if item not in newList:
            newList.append(item)
    print newList
    

    我没有口译员,但逻辑似乎合理。

    【讨论】:

    • 这也给了我 ['a', 'b', 'c', 'd', 'e'],我需要输出为 ['a', 'b', ' d']
    【解决方案2】:
    t = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
    print [a for a in t if t.count(a) == 1]
    

    【讨论】:

      【解决方案3】:

      使用collections.Counter() object,然后只保留计数为 1 的值:

      from collections import counter
      
      [k for k, v in Counter(lst).items() if v == 1]
      

      这是一个 O(N) 算法;您只需要遍历 N 个项目的列表一次,然后在更少的项目 (

      如果顺序很重要并且您使用的是 Python

      counts = Counter(lst)
      [k for k in lst if counts[k] == 1]
      

      演示:

      >>> from collections import Counter
      >>> lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
      >>> [k for k, v in Counter(lst).items() if v == 1]
      ['a', 'b', 'd']
      >>> counts = Counter(lst)
      >>> [k for k in lst if counts[k] == 1]
      ['a', 'b', 'd']
      

      两种方法的顺序相同是巧合;对于 Python 3.6 之前的 Python 版本,其他输入可能会导致不同的顺序。

      在 Python 3.6 中,字典的实现发生了变化,现在保留了输入顺序。

      【讨论】:

        【解决方案4】:
        lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
        from collections import Counter
        c = Counter(lst)
        print([k for k,v in c.items() if v == 1 ])
        

        collections.Counter 会统计每个元素的出现次数,我们保留count/value is == 1if v == 1 的元素

        【讨论】:

          【解决方案5】:

          @Padraic:

          如果您的列表是:

          lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
          

          然后

          list(set(lst))
          

          将返回以下内容:

          ['a', 'c', 'b', 'e', 'd']
          

          这不是阿丹卡想要的……

          完全过滤所有重复项可以通过列表推导轻松完成:

          [item for item in lst if lst.count(item) == 1]
          

          这样的输出是:

          ['a', 'b', 'd']
          

          item 代表列表 lst 中的每个项目,但只有在 lst.count(item) 时才会附加到新列表中等于 1,这确保了该项目在原始列表 lst 中只存在一次。

          查看列表理解了解更多信息:Python list comprehension documentation

          【讨论】:

          • 你的算法是二次的
          • 真的吗?带有if的python列表推导具有二次时间复杂度?你能解释一下吗?你的算法的时间复杂度是多少?
          • 你认为 lst.count(item) 在做什么?
          • 您的解决方案有多复杂?
          • 这是一个O(n)算法
          猜你喜欢
          • 1970-01-01
          • 2013-05-11
          • 2019-08-04
          • 2010-11-22
          • 2018-11-25
          • 2021-01-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多