Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/apache-kafka/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中查找字符串中最长的单词_Python - Fatal编程技术网

在python中查找字符串中最长的单词

在python中查找字符串中最长的单词,python,Python,我很难找到Python中最长的单词 这是我的密码 s=“玛丽是一只小羊羔” words=s.split() 最大长度=0 max_word=“” 用文字表示: 如果最大长度

我很难找到Python中最长的单词

这是我的密码

s=“玛丽是一只小羊羔”
words=s.split()
最大长度=0
max_word=“”
用文字表示:
如果最大长度<长度(字):
最大长度=长度(字)
max_word=word
打印(“最长单词:”,最大单词,”(“,最大单词,”)”,sep=“”)
但是,输出显示了两个单词,Mary(4)和Little(6)。 事实上,当我删除word中的“Mary”时,输出显示为(2)和(6)
如何解决此问题?

将打印移到for循环之外:

s = "Mary is a little lamb"
words = s.split()

max_len = 0
max_word = None

for word in words:
    if max_len < len(word):
        max_len = len(word)
        max_word = word

print("longest word: %s(%d)" % (max_word, max_len))

将打印移到for循环之外:

s = "Mary is a little lamb"
words = s.split()

max_len = 0
max_word = None

for word in words:
    if max_len < len(word):
        max_len = len(word)
        max_word = word

print("longest word: %s(%d)" % (max_word, max_len))

将print语句移到循环之外,使其仅在处理完成后打印。正如您所写的,print语句位于lop内部,因此它在每个循环迭代中都会打印。仅供参考,Python有一个
max()
函数,该函数使用一个键:
max(s.split(),key=len)
将print语句移到循环之外,因此它只在处理完成后打印。正如您所写的,print语句在lop中,因此它在每个循环迭代中都会打印。仅供参考,Python有一个
max()
函数,该函数接受一个键:
max(s.split(),key=len)