要消除列表中的重复项,您可以维护一个辅助列表并进行检查。
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']