有没有办法用 if 语句方法来简化这个列表理解?

我正在尝试获取一个字符串并从超过 4 个字符的单词中删除元音。


有没有更有效的方法来编写这段代码?


(1) 从字符串中创建一个数组。


(2) 遍历一个数组并从超过 4 个字符的字符串中删除元音。


(3) 将数组中的字符串连接到新字符串。


谢谢!


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 sentence



print(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"


拉丁的传说
浏览 163回答 2
2回答

临摹微笑

您可以避免使用外部for,因为您已经在内部进行了迭代。另一方面,您可以将多个replaces 替换为另一个列表推导式,该推导式将嵌套在现有推导式中。# for words in split_string:&nbsp; &nbsp;<- This line is not requiredvowels = '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或者将字符串部分的形成抽象到一个新函数中,这可能会增加它的可读性:def form_word(words):&nbsp; &nbsp; vowels = 'aeiou'&nbsp; &nbsp; return ''.join([x for x in words if x.lower() not in vowels])def abbreviate_sentence(sent):&nbsp; &nbsp; split_string = sent.split()&nbsp; &nbsp; abbrev = [form_word(words) if len(words) > 4 else words for words in split_string]&nbsp; &nbsp; sentence = " ".join(abbrev)&nbsp; &nbsp; return sentence

梦里花落0921

奥斯汀的解决方案或以下解决方案都应该有效。我认为两者在计算上都不会比您现在拥有的效率高得多,因此我将重点放在可读性和合理性上。def abbreviate_sentence(sent):&nbsp; &nbsp; abbrev = []&nbsp; &nbsp; for word in sent.split():&nbsp; &nbsp; &nbsp; &nbsp; if len(word) > 4:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; abbrev.append(words.replace("a", "").replace("e", "").replace("i", "").replace("o", "").replace("u", ""))&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; abbrev.append(word)&nbsp; &nbsp; return " ".join(abbrev)print(abbreviate_sentence("follow the yellow brick road"))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python