Getting first n unique elements from Python list

后端 未结 12 1093
無奈伤痛
無奈伤痛 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:56

    You can adapt the popular itertools unique_everseen recipe:

    def unique_everseen_limit(iterable, limit=5):
        seen = set()
        seen_add = seen.add
        for element in iterable:
            if element not in seen:
                seen_add(element)
                yield element
            if len(seen) == limit:
                break
    
    a = [1,2,2,3,3,4,5,6]
    
    res = list(unique_everseen_limit(a))  # [1, 2, 3, 4, 5]
    

    Alternatively, as suggested by @Chris_Rands, you can use itertools.islice to extract a fixed number of values from a non-limited generator:

    from itertools import islice
    
    def unique_everseen(iterable):
        seen = set()
        seen_add = seen.add
        for element in iterable:
            if element not in seen:
                seen_add(element)
                yield element
    
    res = list(islice(unique_everseen(a), 5))  # [1, 2, 3, 4, 5]
    

    Note the unique_everseen recipe is available in 3rd party libraries via more_itertools.unique_everseen or toolz.unique, so you could use:

    from itertools import islice
    from more_itertools import unique_everseen
    from toolz import unique
    
    res = list(islice(unique_everseen(a), 5))  # [1, 2, 3, 4, 5]
    res = list(islice(unique(a), 5))           # [1, 2, 3, 4, 5]
    

提交回复
热议问题