Getting first n unique elements from Python list

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

    Given

    import itertools as it
    
    
    a = [1, 2, 2, 3, 3, 4, 5, 6]
    

    Code

    A simple list comprehension (similar to @cdlane's answer).

    [k for k, _ in it.groupby(a)][:5]
    # [1, 2, 3, 4, 5]
    

    Alternatively, in Python 3.6+:

    list(dict.fromkeys(a))[:5]
    # [1, 2, 3, 4, 5]
    

提交回复
热议问题