Getting first n unique elements from Python list

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

    a = [1,2,2,3,3,4,5,6]
    
    from collections import defaultdict
    def function(lis,n):
        dic = defaultdict(int)
    
        sol=set()
    
        for i in lis:
                try:
                    if dic[i]:
                        pass
                    else:
                        sol.add(i)
                        dic[i]=1
                        if len(sol)>=n:
                            break
                except KeyError:
                    pass
    
        return list(sol)
    
    print(function(a,3))
    

    output

    [1, 2, 3]
    

提交回复
热议问题