【问题标题】:python : the longest word in a stringpython:字符串中最长的单词
【发布时间】:2022-01-01 09:45:02
【问题描述】:

我正在开发一个从字符串中返回最长单词的函数,我的代码是:

def longestWord(sen):
    max = 1
    i = 0
    ind = 1
    while ind != 0 :
        if sen[i] == " ":
            i = i+1
        word = ""
        lenth = 0

        while(sen[i] != " " and i < len(sen)):
            word = word + sen[i]
            lenth = lenth+1
            if(lenth > max):
                max = lenth
                longestword = word
            i = i+1
            if i == len(sen)-1:
                ind = 0



    return longestword

print(longestWord("ceci est un texte"))

当我尝试运行它时,会出现一个错误提示“字符串索引超出范围”

错误信息:

Traceback (most recent call last):
      File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 25, in <module>
        print(longestWord("ceci est un texte"))
      File "C:\Users\pc\PycharmProjects\pythonProject2\venv\tp2\longestWord.py", line 11, in longestWord
        while(sen[i] != " " and i < len(sen)):
    IndexError: string index out of range

【问题讨论】:

  • 你的问题是“字符串索引超出范围”是什么意思?
  • 字符串"ceci est un texte"的预期输出是什么
  • 因为代码是非pythonic。对于初学者,请尝试交换 sen[i] != " "i &lt; len(sen)
  • 你需要检查长度firstwhile i &lt; len(sen) and sen[i] != " ":否则你在确认isen的合法索引之前尝试访问sen[i]。跨度>
  • 请注意代码的缩进。仅在第一行之前添加四个空格不足以正确格式化代码。请阅读formatting help

标签: python string loops


【解决方案1】:

您可以在一行中完成此操作

def longest_word(sentence): 
    return sorted(sencente.split(), key = lambda x: len(x))[-1]

print(longest_word("ceci est un texte"))

【讨论】:

  • 为什么不直接使用max
  • 你说得对 max 更好
  • 您也可以使用reverse 参数到sorted 并获取第一个元素。 sorted(sencente.split(), key = lambda x: len(x), reverse = True)[0]
  • true 但 [-1]reverse = True
【解决方案2】:

用这个替换你的函数:

def longestWord(string) :
    lettersCounter = 0
    result = ""
    for word in string.split() :
        if(len(word) > lettersCounter) :
            lettersCounter = len(word)
            result = word

    return result

print(longestWord("ceci est un texte"))

【讨论】:

    【解决方案3】:

    似乎是一个非常复杂的方法。一个简单的pythonic方式是:

    def longest_word(s):
        return max(s.split(), key=len)
    

    输出:

    >>> longest_word("ceci est un texte")
    "texte"
    

    【讨论】:

      【解决方案4】:

      如果你想将结果捕获在一个列表中,因为多个个单词的长度可能相同。

      def longest_words(sentence):
          words = sentence.split()
          maxlen = max(len(w) for w in words)
          return [w for w in words if len(w) == maxlen]
      

      或者一次通过:

      def longest_words(sentence):
      
          words = sentence.split()
          results = []
          maxlen = 0
      
          for w in words:
      
              curlen = len(w)
      
              if curlen > maxlen:
                  results = [w]
                  maxlen = curlen
              elif curlen == maxlen:
                  results.append(w)
      
          return results
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-04-18
        • 2020-03-04
        • 1970-01-01
        • 1970-01-01
        • 2020-08-22
        • 2018-11-25
        • 1970-01-01
        • 2016-05-28
        相关资源
        最近更新 更多