第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何更優(yōu)雅地編寫這些嵌套的 if 語(yǔ)句?

如何更優(yōu)雅地編寫這些嵌套的 if 語(yǔ)句?

眼眸繁星 2022-07-05 17:16:30
我正在編寫一個(gè)從文件中刪除重復(fù)單詞的 python 程序。單詞被定義為任何不帶空格的字符序列,無(wú)論大小寫如何,重復(fù)都是重復(fù)的,因此:duplicate、Duplicate、DUPLICATE、dUplIcaTe 都是重復(fù)的。它的工作方式是我讀入原始文件并將其存儲(chǔ)為字符串列表。然后我創(chuàng)建一個(gè)新的空列表并一次填充一個(gè),檢查當(dāng)前字符串是否已存在于新列表中。當(dāng)我嘗試實(shí)現(xiàn)大小寫轉(zhuǎn)換時(shí)遇到問(wèn)題,它會(huì)檢查特定大小寫格式的所有實(shí)例。我嘗試將 if 語(yǔ)句重寫為: if elem and capital and title and lower not in uniqueList:     uniqueList.append(elem)我也試過(guò)用 or 語(yǔ)句來(lái)寫它: if elem or capital or title or lower not in uniqueList:     uniqueList.append(elem)但是,我仍然得到重復(fù)。程序正常工作的唯一方法是如果我這樣編寫代碼: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有什么方法可以更優(yōu)雅地編寫這些嵌套的 if 語(yǔ)句?
查看完整描述

2 回答

?
紅顏莎娜

TA貢獻(xiàn)1842條經(jīng)驗(yàn) 獲得超13個(gè)贊

將測(cè)試與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):

但是,與其測(cè)試所有不同形式的elem,不如一開始只輸入小寫單詞會(huì)更簡(jiǎn)單self.words

并制作self.wordsaset而不是 a list,然后將自動(dòng)刪除重復(fù)項(xiàng)。


查看完整回答
反對(duì) 回復(fù) 2022-07-05
?
LEATH

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊

如果要保留輸入中的原始大寫/小寫,請(qǐng)檢查以下內(nèi)容:


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


查看完整回答
反對(duì) 回復(fù) 2022-07-05
  • 2 回答
  • 0 關(guān)注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)