Retrieve only non-duplicate elements from a list

后端 未结 2 364
误落风尘
误落风尘 2021-01-27 14:49

What is the best option to retrieve only non-duplicate elements from a Python list? Say I have the following list:

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

I w

相关标签:
2条回答
  • 2021-01-27 15:26

    This is a breeze with a list comprehension:

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

    Also, I recommend that you do not name a variable list--it overshadows the built-in.

    0 讨论(0)
  • 2021-01-27 15:35

    Use collections.Counter to get counts of items. Combine with a list comprehension to keep only those that have a count of one.

    >>> from collections import Counter
    >>> lst = [1, 2, 3, 2, 3, 4]
    >>> [item for item, count in Counter(lst).items() if count == 1]
    [1, 4]
    
    0 讨论(0)
提交回复
热议问题