比较字符串中单词的长度

2024-06-11 00:31:12 发布

您现在位置:Python中文网/ 问答频道 /正文

需要找到字符串中最长的单词并打印该单词。 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周的学生。


Tags: to字符串用户def单词句子word空格
3条回答
def longestWord(sentence):
    longest = 0   # Keep track of the longest length
    word = ''     # And the word that corresponds to that length
    for i in sentence.split():
        if len(i) > longest:
            word = i
            longest = len(i)
    return word

>>> s = 'this is a test sentence with some words'
>>> longestWord(s)
'sentence'

你的方向是对的。你的大部分代码看起来不错,你只需要完成逻辑就可以确定哪个是最长的单词。因为这看起来像是一个家庭作业问题,我不想给你直接的答案(尽管其他人都有,我认为这对你这样的学生没用),但有多种方法可以解决这个问题。

你得到了每个单词的正确长度,但是你需要将每个单词的长度与之进行比较吗?试着大声说出问题,以及你个人如何大声解决问题。我想你会发现你的英文描述很好地翻译成了python版本。

另一个不使用if语句的解决方案可能使用内置的python函数max,该函数接受一个数字列表并返回最大值。你怎么能用这个?

可以将max与键一起使用:

def max_word(splitlist):      
    return max(splitlist.split(),key=len) if splitlist.strip() else "" # python 2


def max_word(splitlist): 
    return max(splitlist.split()," ",key=len) # python 3

或者使用try/除非jon clements建议:

def max_word(splitlist):
    try:
        return max(splitlist.split(),key=len)
    except ValueError:
        return " "

相关问题 更多 >