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

后端 未结 8 1606
渐次进展
渐次进展 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:59

    A good alternative to using a set would be to use a dictionary. The collections module contains a class called Counter which is specialized dictionary for counting the number of times each of its keys are seen. Using it you could do something like this:

    from collections import Counter
    
    wordlist = ['Arise', 'But', 'It', 'Juliet', 'Who', 'already', 'and', 'and',
                'and', 'breaks', 'east', 'envious', 'fair', 'grief', 'is', 'is',
                'is', 'kill', 'light', 'moon', 'pale', 'sick', 'soft', 'sun', 'sun',
                'the', 'the', 'the', 'through', 'what', 'window', 'with', 'yonder']
    
    newlist = sorted(Counter(wordlist), 
                     key=lambda w: w.lower())  # case insensitive sort
    print(newlist)
    

    Output:

    ['already', 'and', 'Arise', 'breaks', 'But', 'east', 'envious', 'fair',
     'grief', 'is', 'It', 'Juliet', 'kill', 'light', 'moon', 'pale', 'sick',
     'soft', 'sun', 'the', 'through', 'what', 'Who', 'window', 'with', 'yonder']
    

提交回复
热议问题