我在试着学习蟒蛇。以下是练习的相关部分:
对于每个单词,检查该单词是否已在列表中。如果单词不在列表中,则将其添加到列表中。
这就是我所得到的。
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等)。
如何只获取唯一的值?
发布于 2017-02-20 07:30:49
要从列表中消除重复项,您可以维护一个辅助列表并进行检查。
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)
输出:
['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()
set对象是不同的
对象的无序集合。
Hashability使对象可用作字典键和集成员,因为这些数据结构在内部使用散列值。
由于哈希表中成员关系检查的平均情况为O(1),因此使用集合更有效。
auxiliaryList = list(set(myList))
输出:
['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']
发布于 2017-02-20 07:30:36
您应该使用not in
运算符而不是is not
运算符来检查该项是否在列表中:
if word not in output:
顺便说一句,使用set
非常有效(参见Time complexity):
with open('romeo.txt') as fhand:
output = set()
for line in fhand:
words = line.split()
output.update(words)
UPDATE set
不会保留原始顺序。要保留顺序,请使用集合作为辅助数据结构:
output = []
seen = set()
with open('romeo.txt') as fhand:
for line in fhand:
words = line.split()
for word in words:
if word not in seen: # faster than `word not in output`
seen.add(word)
output.append(word)
发布于 2018-06-27 15:51:52
一种方法是在添加之前查看它是否在列表中,这就是Tony的答案。如果要在列表创建后删除重复的值,可以使用set()
将现有列表转换为一组唯一值,然后使用list()
将其再次转换为列表。只有一行代码:
list(set(output))
如果你想按字母顺序排序,只需在上面添加一个sorted()
即可。结果如下:
['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']
https://stackoverflow.com/questions/42334197
复制相似问题