需要找到字符串中最长的单词并打印该单词。 1.)要求用户输入用空格分隔的句子。 2)找到并打印最长的单词。如果两个或多个单词的长度与打印第一个单词的长度相同。
这就是我目前所拥有的
def maxword(splitlist): #sorry, still trying to understand loops
for word in splitlist:
length = len(word)
if ??????
wordlist = input("Enter a sentence: ")
splitlist = wordlist.split()
maxword(splitlist)
我想比较一句话中的字数时,我撞到了墙。我是一个已经使用python 5周的学生。
你的方向是对的。你的大部分代码看起来不错,你只需要完成逻辑就可以确定哪个是最长的单词。因为这看起来像是一个家庭作业问题,我不想给你直接的答案(尽管其他人都有,我认为这对你这样的学生没用),但有多种方法可以解决这个问题。
你得到了每个单词的正确长度,但是你需要将每个单词的长度与之进行比较吗?试着大声说出问题,以及你个人如何大声解决问题。我想你会发现你的英文描述很好地翻译成了python版本。
另一个不使用
if
语句的解决方案可能使用内置的python函数max
,该函数接受一个数字列表并返回最大值。你怎么能用这个?可以将max与键一起使用:
或者使用try/除非jon clements建议:
相关问题 更多 >
编程相关推荐