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

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

有沒有辦法用 if 語句方法來簡化這個(gè)列表理解?

有沒有辦法用 if 語句方法來簡化這個(gè)列表理解?

拉丁的傳說 2022-06-02 17:28:23
我正在嘗試獲取一個(gè)字符串并從超過 4 個(gè)字符的單詞中刪除元音。有沒有更有效的方法來編寫這段代碼?(1) 從字符串中創(chuàng)建一個(gè)數(shù)組。(2) 遍歷一個(gè)數(shù)組并從超過 4 個(gè)字符的字符串中刪除元音。(3) 將數(shù)組中的字符串連接到新字符串。謝謝!def abbreviate_sentence(sent):    split_string = sent.split()    for words in split_string:        abbrev = [words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", "")                        if len(words) > 4 else words for words in split_string]        sentence = " ".join(abbrev)        return sentenceprint(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"
查看完整描述

2 回答

?
臨摹微笑

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

您可以避免使用外部for,因?yàn)槟呀?jīng)在內(nèi)部進(jìn)行了迭代。另一方面,您可以將多個(gè)replaces 替換為另一個(gè)列表推導(dǎo)式,該推導(dǎo)式將嵌套在現(xiàn)有推導(dǎo)式中。


# for words in split_string:   <- This line is not required

vowels = 'aeiou'

abbrev = [''.join([x for x in words if x.lower() not in vowels]) if len(words) > 4 else words for words in split_string]

sentence = " ".join(abbrev)

return sentence

或者將字符串部分的形成抽象到一個(gè)新函數(shù)中,這可能會(huì)增加它的可讀性:


def form_word(words):

    vowels = 'aeiou'

    return ''.join([x for x in words if x.lower() not in vowels])


def abbreviate_sentence(sent):

    split_string = sent.split()

    abbrev = [form_word(words) if len(words) > 4 else words for words in split_string]

    sentence = " ".join(abbrev)

    return sentence


查看完整回答
反對(duì) 回復(fù) 2022-06-02
?
夢里花落0921

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

奧斯汀的解決方案或以下解決方案都應(yīng)該有效。我認(rèn)為兩者在計(jì)算上都不會(huì)比您現(xiàn)在擁有的效率高得多,因此我將重點(diǎn)放在可讀性和合理性上。


def abbreviate_sentence(sent):

    abbrev = []

    for word in sent.split():

        if len(word) > 4:

            abbrev.append(words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", ""))

        else:

            abbrev.append(word)

    return " ".join(abbrev)



print(abbreviate_sentence("follow the yellow brick road"))


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

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號(hào)

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