Getting first n unique elements from Python list

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

    You can use OrderedDict or, since Python 3.7, an ordinary dict, since they are implemented to preserve the insertion order. Note that this won't work with sets.

    N = 3
    a = [1, 2, 2, 3, 3, 3, 4]
    d = {x: True for x in a}
    list(d.keys())[:N]
    

提交回复
热议问题