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

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

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

拉丁的传说 2022-06-02 17:28:23
我正在尝试获取一个字符串并从超过 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 sentenceprint(abbreviate_sentence("follow the yellow brick road"))      # => "fllw the yllw brck road"
查看完整描述

2 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

您可以避免使用外部for,因为您已经在内部进行了迭代。另一方面,您可以将多个replaces 替换为另一个列表推导式,该推导式将嵌套在现有推导式中。


# 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

或者将字符串部分的形成抽象到一个新函数中,这可能会增加它的可读性:


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


查看完整回答
反对 回复 2022-06-02
?
梦里花落0921

TA贡献1772条经验 获得超6个赞

奥斯汀的解决方案或以下解决方案都应该有效。我认为两者在计算上都不会比您现在拥有的效率高得多,因此我将重点放在可读性和合理性上。


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"))


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

添加回答

举报

0/150
提交
取消
微信客服

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

帮助反馈 APP下载

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

公众号

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