为了账号安全,请及时绑定邮箱和手机立即绑定

如何更优雅地编写这些嵌套的 if 语句?

如何更优雅地编写这些嵌套的 if 语句?

眼眸繁星 2022-07-05 17:16:30
我正在编写一个从文件中删除重复单词的 python 程序。单词被定义为任何不带空格的字符序列,无论大小写如何,重复都是重复的,因此:duplicate、Duplicate、DUPLICATE、dUplIcaTe 都是重复的。它的工作方式是我读入原始文件并将其存储为字符串列表。然后我创建一个新的空列表并一次填充一个,检查当前字符串是否已存在于新列表中。当我尝试实现大小写转换时遇到问题,它会检查特定大小写格式的所有实例。我尝试将 if 语句重写为: if elem and capital and title and lower not in uniqueList:     uniqueList.append(elem)我也试过用 or 语句来写它: 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 语句?
查看完整描述

2 回答

?
红颜莎娜

TA贡献1842条经验 获得超13个赞

将测试与and

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.wordsaset而不是 a list,然后将自动删除重复项。


查看完整回答
反对 回复 2022-07-05
?
LEATH

TA贡献1936条经验 获得超7个赞

如果要保留输入中的原始大写/小写,请检查以下内容:


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']


查看完整回答
反对 回复 2022-07-05
  • 2 回答
  • 0 关注
  • 137 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号