How can I make my code be a set?

前端 未结 3 689
Happy的楠姐
Happy的楠姐 2021-01-20 04:26

I have a little code that takes a list of objects, and only outputs the items in the list that are unique.

This is my code

def only_once(a):
    retu         


        
3条回答
  •  有刺的猬
    2021-01-20 04:45

    To clarify, what you want is a set of items that appear once, and only once.

    The best option here is to use collections.Counter(), as it means you only count the items once, rather than once per item, greatly increasing performance:

    >>> import collections
    >>> {key for key, count in collections.Counter(a).items() if count == 1}
    {1, 2, 3}
    

    We simply replace the square brackets with curly braces to signify a set comprehension over a list comprehension, to get a set of results.

提交回复
热议问题