Remove duplicates and original from list

后端 未结 5 944
清酒与你
清酒与你 2020-11-29 12:49

Given a list of strings I want to remove the duplicates and original word.

For example:

lst = [\'a\', \'b\', \'c\', \'c\', \'c\', \'d\', \'e\', \'e\']
         


        
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 13:22

    @Padraic:

    If your list is:

    lst = ['a', 'b', 'c', 'c', 'c', 'd', 'e', 'e']
    

    then

    list(set(lst))
    

    would return the following:

    ['a', 'c', 'b', 'e', 'd']
    

    which is not the thing adhankar wants..

    Filtering all duplicates completely can be easily done with a list comprehension:

    [item for item in lst if lst.count(item) == 1]
    

    The output of this would be:

    ['a', 'b', 'd']
    

    item stands for every item in the list lst, but it is only appended to the new list if lst.count(item) equals 1, which ensures, that the item only exists once in the original list lst.

    Look up List Comprehension for more information: Python list comprehension documentation

提交回复
热议问题