用于检查值是否在列表中对 set 不起作用的逻辑



我正在编写一个程序,无论大小写如何,都可以从文件中删除重复的单词。单词被定义为任何没有空格和重复的字符序列,DUPLICATE,Duplicate和DuPliCate都是重复的。

我已经通过读取原始文本作为单词(字符串(列表并通过检查当前单词是否在唯一单词列表中来创建新的唯一字符串列表来使程序工作。如果它不在唯一列表中,请将其追加到列表中;忽略换行符的重复项。

众所周知,使用列表不是很有效,尤其是对于大型文本文件。所以我正在尝试通过使用集合来确定我是否应该将特定单词附加到唯一列表中来实现此功能。

此逻辑有效,但效率低下:

def remove_duplicates(self):
"""
:return: void
Adds each unique word to a new list, checking for all the possible cases.
"""
print("Removing duplicates...")
unique = []
for elem in self.words:
if elem == 'n':
unique.append(elem)
else:
if elem not in unique 
and elem.upper() not in unique 
and elem.title() not in unique 
and elem.lower() not in unique:
unique.append(elem)
self.words = unique

因此,合乎逻辑的做法是使用这样的集合:

def remove_duplicates(self):
"""
:return: void
Adds each unique word to a new list, checking for all the possible cases.        
"""
print("Removing duplicates...")
unique = []
seen = set()
for elem in self.words:
lower = elem.lower()       
seen.add(lower)
if elem == 'n':
unique.append(elem)
else:
if lower not in seen:
unique.append(elem)       
self.words = unique

但是,它似乎不起作用。我最终得到一个空的文本文件。我已经打印了这套,它不是空的。嵌套的 if 语句中似乎存在问题,并且对它可能是什么感到困惑。我一直在尝试调试它几个小时,但没有运气。我什至尝试过编写 if 语句,就像我在低效工作示例中所做的那样,但它仍然给我带来了同样的问题。我不知道为什么它没有将单词附加到唯一。

示例输入:

self.words = ["duplicate", "not", "DUPLICATE", "DuPliCate", "hot"]

预期输出(需要保留原始顺序,仅保留重复单词的第一个实例(:

unique = ["duplicate", "not", "hot"] 

您在检查对象之前将对象添加到seen,因此它始终存在于if语句的seen中。

for elem in self.words:
lower = elem.lower()       
if lower not in seen:
unique.append(elem)
seen.add(lower) # move your seen statement to exist within the check
self.words = unique
return self.words
Removing duplicates...
['duplicate', 'not', 'hot']

最新更新