删除列表中的重复项

时间:2017-12-28 10:21:53

标签: python-3.x list

我正在执行一个程序,使用true函数删除Python中列表中的重复单词。

我的回答是错误的,因为它没有删除重复的元素。

romeo.txt:

split()

我的代码:

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

1 个答案:

答案 0 :(得分:1)

  1. 您需要遍历每个单词,每一行。
  2. 使用append()将字词添加到列表中。
  3. 示例:

    line="But soft what light through yonder window breaks It is the east and Juliet is the sun Arise fair sun and kill the envious moon Who is already sick and pale with grief"
    
    arr=list()
    count=0
    
    words=line.split()
    for word in words:
        if word not in arr: 
           arr.append(word)
    
    arr.sort()
    print(arr)
    

    输出

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