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

我正在编写一个从文件中删除重复单词的 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 语句?


眼眸繁星
浏览 138回答 2
2回答

红颜莎娜

将测试与andif 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,然后将自动删除重复项。

LEATH

如果要保留输入中的原始大写/小写,请检查以下内容: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 elementuniqs = []for key, value in dictionary.items():    if len(value) == 1:        uniqs.extend(value)print(uniqs)# will print ['my', 'naMe', 'Is']
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python