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

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"))
添加回答
舉報(bào)