How do I remove duplicate words from a list in python without using sets?

后端 未结 8 1636
渐次进展
渐次进展 2021-02-11 04:24

I have the following python code which almost works for me (I\'m SO close!). I have text file from one Shakespeare\'s plays that I\'m opening: Original text file:

\"Bu

8条回答
  •  北恋
    北恋 (楼主)
    2021-02-11 04:48

    This should work, it walks the list and adds elements to a new list if they are not the same as the last element added to the new list.

    def unique(lst):
        """ Assumes lst is already sorted """
        unique_list = []
        for el in lst:
            if el != unique_list[-1]:
                unique_list.append(el)
        return unique_list
    

    You could also use collections.groupby which works similarly

    from collections import groupby
    
    # lst must already be sorted 
    unique_list = [key for key, _ in groupby(lst)]
    

提交回复
热议问题