Getting first n unique elements from Python list

后端 未结 12 1102
無奈伤痛
無奈伤痛 2021-02-04 23:59

I have a python list where elements can repeat.

>>> a = [1,2,2,3,3,4,5,6]

I want to get the first n unique elements from

12条回答
  •  余生分开走
    2021-02-05 00:34

    If your objects are hashable (ints are hashable) you can write utility function using fromkeys method of collections.OrderedDict class (or starting from Python3.7 a plain dict, since they became officially ordered) like

    from collections import OrderedDict
    
    
    def nub(iterable):
        """Returns unique elements preserving order."""
        return OrderedDict.fromkeys(iterable).keys()
    

    and then implementation of iterate can be simplified to

    from itertools import islice
    
    
    def iterate(itr, upper=5):
        return islice(nub(itr), upper)
    

    or if you want always a list as an output

    def iterate(itr, upper=5):
        return list(nub(itr))[:upper]
    

    Improvements

    As @Chris_Rands mentioned this solution walks through entire collection and we can improve this by writing nub utility in a form of generator like others already did:

    def nub(iterable):
        seen = set()
        add_seen = seen.add
        for element in iterable:
            if element in seen:
                continue
            yield element
            add_seen(element)
    

提交回复
热议问题