如何为这个问题写一个循环函数?

时间:2019-04-03 13:59:03

标签: python

我被卡了2个小时:( 编写一个名为length_of_longest_word的函数,该函数接受一个名为word_list的列表变量作为参数,并返回该列表中最长单词的长度。提示:使用如下语句初始化循环上方的变量:max_length =0。然后,在循环体中,使用max函数将max_length值与当前单词的长度进行比较,例如:max(max_length ,length_of_current_word),然后使用新值适当更新max_length。如果迷路了,请尝试在循环中添加一些打印语句!

answer:

assert length_of_longest_word(["these", "are", "diminuitive", "words"]) == 11
assert length_of_longest_word(["short", "tiny", "haha", "antidisestablishmentarianism"]) == 28

我自己的作品停在这里:

max_length = 0 def length_of_longest_word(word_list):     对于(word_list)中的项目:         abb = max_length + len(项目)         打印(abb)

return max(abb)

length_of_longest_word([“这些”,“是”,“身分”,“单词”])

(弹出拼写错误)

1 个答案:

答案 0 :(得分:0)

def length_of_longest_word(word_list):
    max_length = 0
    for word in word_list:
        max_length = max(max_length,len(word))
    return max_length

print (length_of_longest_word(["these", "are", "diminuitive", "words"]))