Getting first n unique elements from Python list

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

    There are really amazing answers for this question, which are fast, compact and brilliant! The reason I am putting here this code is that I believe there are plenty of cases when you don't care about 1 microsecond time loose nor you want additional libraries in your code for one-time solving a simple task.

    a = [1,2,2,3,3,4,5,6]
    res = []
    for x in a:
        if x not in res:  # yes, not optimal, but doesnt need additional dict
            res.append(x)
            if len(res) == 5:
                break
    print(res)
    

提交回复
热议问题