繁体   English   中英

删除列表中的重复元素 [重复]

[英]Removing duplicate elements in a list [duplicate]

这个问题在这里已经有了答案:

这是我已经做了好几个小时的家庭作业。 已经取得了进展,但我已经走到了尽头。 我有一个文本文件,已将其转换为按字母顺序排序的单词列表(包括一些大写单词)。 最后要做的是从列表中删除重复的单词 我找到了关于从列表中删除项目的问题的答案,但没有找到关于删除重复项目的答案。 我已经建立了一个循环——由于我无法理解的原因——只适用于原始列表的一半。

这是我尝试过的代码:

fhand=open('romeo.txt')
data=fhand.read()
data=data.split()
data[0]='but'
data[8]='it'
data[13]='juliet'
data[17]='arise'
data[25]='who'
data.sort()
newlist=[]
for x in data:
    if data[0] == data[1]:
        del data[0]
    elif data[0] != data[1]:
        newlist.append(data[0])
    del data [0]
print(newlist)

原始分割文本文件为: ['but', 'soft', 'what', 'light', 'through', 'yonder', 'window', 'breaks', 'it', 'is', 'the' , '东方', 'and', 'juliet', 'is', 'the', 'sun', 'arise', 'fair', 'sun', 'and', 'kill', 'the', '羡慕','月亮','谁','是','已经','生病','和','苍白','与','悲伤']

预期 output 是: ['已经','和','出现','休息','但是','东方','羡慕','公平','悲伤','是','它',' juliet','kill','light','moon','pale','sick','soft','sun','sun','the','the','the','through' , 'what', 'who', 'window', 'with', 'yonder']

实际 output 是: ['已经','and','arise','breaks','but','east','envious','fair','grief','is','it','朱丽叶','杀死','光']

所以循环做了它应该做的事情,但在“光”之后退出。 想不通这个。

这不是从列表中删除重复项的好方法。 此外,您不应在像这样迭代列表时从列表中删除元素。 考虑改用一个集合。 集合没有排序,但由于您在处理数据之前对数据进行了排序,因此您可以使用sorted将无序集合转换为排序列表。

data = ['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']

new_data = sorted(set(data))

print(new_data)

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']

您也可以在没有集合和没有del的循环中执行此操作:

newlist = []

for x in sorted(data):
    if x not in newlist:
        newlist.append(x)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM