Getting first n unique elements from Python list

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

    Assuming the elements are ordered as shown, this is an opportunity to have fun with the groupby function in itertools:

    from itertools import groupby, islice
    
    def first_unique(data, upper):
        return islice((key for (key, _) in groupby(data)), 0, upper)
    
    a = [1, 2, 2, 3, 3, 4, 5, 6]
    
    print(list(first_unique(a, 5)))
    

    Updated to use islice instead of enumerate per @juanpa.arrivillaga. You don't even need a set to keep track of duplicates.

提交回复
热议问题