【问题标题】:Retrieve only non-duplicate elements from a list仅从列表中检索非重复元素
【发布时间】:2013-10-17 14:50:35
【问题描述】:

从 Python 列表中仅检索非重复元素的最佳选择是什么?假设我有以下列表:

lst = [1, 2, 3, 2, 3, 4]

我想检索以下内容:

lst = [1, 4]

23 在该列表中不是唯一的,因此不会被检索到)

【问题讨论】:

    标签: python unique


    【解决方案1】:

    使用collections.Counter 获取项目计数。结合列表推导,只保留计数为 1 的那些。

    >>> from collections import Counter
    >>> lst = [1, 2, 3, 2, 3, 4]
    >>> [item for item, count in Counter(lst).items() if count == 1]
    [1, 4]
    

    【讨论】:

      【解决方案2】:

      list comprehension 轻而易举:

      >>> lst = [1, 2, 3, 2, 3, 4]
      >>> [x for x in lst if lst.count(x) == 1]
      [1, 4]
      >>>
      

      另外,我建议您不要将变量命名为 list——它会掩盖内置变量。

      【讨论】:

      • 更改了变量名。谢谢你的回答。
      • 这可行,但请注意,由于嵌套循环(count 被实现为循环),随着列表变大,性能会迅速下降。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多