Python list comprehension Remove duplicates

后端 未结 2 1626
孤街浪徒
孤街浪徒 2021-01-27 07:32

I want unique elements in hubcode_list. I can do it by

hubcode_alarm_obj = HubAlarm.objects.all()
for obj in hubcode_alarm_obj:
    hubcode = obj.h         


        
2条回答
  •  心在旅途
    2021-01-27 07:56

    Your answer is no. List comprehension creates a completely new list all at one shot, so you can't check to see if something exists:

    >>> lst = [1, 2, 2, 4, 5, 5, 5, 6, 7, 7, 3, 3, 4]
    >>> new = [item for item in lst if item not in new]
    Traceback (most recent call last):
      File "", line 1, in 
    NameError: name 'new' is not defined
    >>> 
    

    Therefore, the preferred one-liner is to use list(set(...)).

    >>> lst = [1, 2, 2, 4, 5, 5, 5, 6, 7, 7, 3, 3, 4]
    >>> list(set(lst))
    [1, 2, 3, 4, 5, 6, 7]
    >>> 
    

    However, in a list of lists, this would not work:

    >>> lst = [[1, 2], [1, 2], [3, 5], [6, 7]]
    >>> list(set(lst))
    Traceback (most recent call last):
      File "", line 1, in 
    TypeError: unhashable type: 'list'
    >>> 
    

    In that case, use the standard for loop and .append().

提交回复
热议问题