Python 用于检查值是否在列表中不适用于集合的逻辑
我正在写一个程序,不管大小写,都可以从文件中删除重复的单词。单词定义为没有空格的任何字符序列,重复、重复、重复和重复都是重复的 我通过读取原始文本中的单词(字符串)列表,并通过检查当前单词是否在唯一单词列表中来创建一个新的唯一字符串列表,从而使程序正常工作。如果它不在唯一列表中,请将其附加到列表中;忽略换行符的重复项 很多人都知道,使用列表不是很有效,尤其是对于大型文本文件。因此,我试图通过使用一个集合来实现这个函数,以确定是否应该在唯一列表中附加一个特定的单词 这种逻辑可行,但效率低下:Python 用于检查值是否在列表中不适用于集合的逻辑,python,python-3.x,list,set,logic,Python,Python 3.x,List,Set,Logic,我正在写一个程序,不管大小写,都可以从文件中删除重复的单词。单词定义为没有空格的任何字符序列,重复、重复、重复和重复都是重复的 我通过读取原始文本中的单词(字符串)列表,并通过检查当前单词是否在唯一单词列表中来创建一个新的唯一字符串列表,从而使程序正常工作。如果它不在唯一列表中,请将其附加到列表中;忽略换行符的重复项 很多人都知道,使用列表不是很有效,尤其是对于大型文本文件。因此,我试图通过使用一个集合来实现这个函数,以确定是否应该在唯一列表中附加一个特定的单词 这种逻辑可行,但效率低下: de
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语句,但它仍然给了我同样的问题。我不明白为什么它不在unique后面加上这些词
样本输入:
self.words = ["duplicate", "not", "DUPLICATE", "DuPliCate", "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']
您是否能够提供示例数据和预期输出?如果有错误,也请检查错误。
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']