仅将唯一值添加到 python 中的列表中

2023-12-25

我正在努力学习Python。以下是练习的相关部分:

对于每个单词,检查该单词是否已在列表中。如果 该单词不在列表中,请将其添加到列表中。

这是我所拥有的。

fhand = open('romeo.txt')
output = []

for line in fhand:
    words = line.split()
    for word in words:
        if word is not output:
            output.append(word)

print sorted(output)

这是我得到的。

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

注意重复(and、is、sun 等)。

如何只获得唯一值?


要消除列表中的重复项,您可以维护一个辅助列表并进行检查。

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

auxiliaryList = []
for word in myList:
    if word not in auxiliaryList:
        auxiliaryList.append(word)

output:

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

这非常容易理解,并且代码是不言自明的。然而,代码简单性是以代码效率为代价的,因为对不断增长的列表的线性扫描会使线性算法退化为二次算法。


如果顺序不重要,您可以使用set() https://docs.python.org/3.6/library/stdtypes.html#set-types-set-frozenset

集合对象是不同的可哈希对象的无序集合。

可哈希性 https://docs.python.org/3.6/glossary.html#term-hashable使对象可用作字典键和集合成员,因为这些数据结构在内部使用哈希值。

自从average哈希表中的成员资格检查的情况是 O(1),使用集合效率更高。

auxiliaryList = list(set(myList))

output:

['and', 'envious', 'already', 'fair', 'is', 'through', 'pale', 'yonder', 
 'what', 'sun', 'Who', 'But', 'moon', 'window', 'sick', 'east', 'breaks', 
 'grief', 'with', 'light', 'It', 'Arise', 'kill', 'the', 'soft', 'Juliet']
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅将唯一值添加到 python 中的列表中 的相关文章

随机推荐