Getting first n unique elements from Python list

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

    Example list:

    a = [1, 2, 2, 3, 3, 4, 5, 6]
    

    Function returns all or count of unique items needed from list

    1st argument - list to work with, 2nd argument (optional) - count of unique items (by default - None - it means that all unique elements will be returned)

    def unique_elements(lst, number_of_elements=None):
        return list(dict.fromkeys(lst))[:number_of_elements]
    

    Here is example how it works. List name is "a", and we need to get 2 unique elements:

    print(unique_elements(a, 2))
    

    Output:

提交回复
热议问题