Getting first n unique elements from Python list

后端 未结 12 1098
無奈伤痛
無奈伤痛 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条回答
  •  -上瘾入骨i
    2021-02-05 00:55

    Here is a Pythonic approach using itertools.takewhile():

    In [95]: from itertools import takewhile
    
    In [96]: seen = set()
    
    In [97]: set(takewhile(lambda x: seen.add(x) or len(seen) <= 4, a))
    Out[97]: {1, 2, 3, 4}
    

提交回复
热议问题