Python 如何更优雅地编写这些嵌套if语句?
我正在编写一个python程序,从文件中删除重复的单词。单词被定义为任何不带空格的字符序列,并且无论大小写,重复都是重复的,因此:重复、重复、重复、重复都是重复的。它的工作方式是读取原始文件并将其存储为字符串列表。然后,我创建一个新的空列表并一次填充一个,检查当前字符串是否已经存在于新列表中。我在尝试实现case转换时遇到问题,该转换检查特定case格式的所有实例。我尝试将if语句改写为:Python 如何更优雅地编写这些嵌套if语句?,python,python-3.x,file,if-statement,nested,Python,Python 3.x,File,If Statement,Nested,我正在编写一个python程序,从文件中删除重复的单词。单词被定义为任何不带空格的字符序列,并且无论大小写,重复都是重复的,因此:重复、重复、重复、重复都是重复的。它的工作方式是读取原始文件并将其存储为字符串列表。然后,我创建一个新的空列表并一次填充一个,检查当前字符串是否已经存在于新列表中。我在尝试实现case转换时遇到问题,该转换检查特定case格式的所有实例。我尝试将if语句改写为: if elem and capital and title and lower not in uniqu
if elem and capital and title and lower not in uniqueList:
uniqueList.append(elem)
我也试着用或语句来写:
if elem or capital or title or lower not in uniqueList:
uniqueList.append(elem)
然而,我仍然得到重复。程序正常运行的唯一方法是,如果我这样编写代码:
def remove_duplicates(self):
"""
self.words is a class variable, which stores the original text as a list of strings
"""
uniqueList = []
for elem in self.words:
capital = elem.upper()
lower = elem.lower()
title = elem.title()
if elem == '\n':
uniqueList.append(elem)
else:
if elem not in uniqueList:
if capital not in uniqueList:
if title not in uniqueList:
if lower not in uniqueList:
uniqueList.append(elem)
self.words = uniqueList
有什么方法可以更优雅地编写这些嵌套的if语句吗?将测试与
和
结合起来
if elem not in uniqueList and capital not in uniqueList and title not in uniqueList and lower not in uniqueList:
也可以使用集合操作:
if not set((elem, capital, title, lower)).isdisjoint(uniqueList):
但是,与其测试所有不同形式的elem
,不如在self.words
中只放小写单词
并将
self.words
设置为set
而不是列表
,则重复项将自动删除。如果要保留输入中的原始大写/小写,请选中此项:
content = "Hello john hello hELLo my naMe Is JoHN"
words = content.split()
dictionary = {}
for word in words:
if word.lower() not in dictionary:
dictionary[word.lower()] = [word]
else:
dictionary[word.lower()].append(word)
print(dictionary)
# here we have dictionary: {'hello': ['Hello', 'hello', 'hELLo'], 'john': ['john', 'JoHN'], 'my': ['my'], 'name': ['naMe'], 'is': ['Is']}
# we want the value of the keys that their list contains a single element
uniqs = []
for key, value in dictionary.items():
if len(value) == 1:
uniqs.extend(value)
print(uniqs)
# will print ['my', 'naMe', 'Is']
如果elem和大写字母以及title和lower不在uniqueList中:
不起作用,您需要编写如果elem和大写字母不在uniqueList中,大写字母不在uniqueList中,title和lower不在uniqueList中:
首先将所有内容转换为小写,然后进行比较。例如,如果elem.lower()不在唯一列表中