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
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"))
添加回答
举报
