【问题标题】:Comparing lengths of words in strings比较字符串中单词的长度
【发布时间】:2014-11-23 19:59:02
【问题描述】:

需要在字符串中找到最长的单词并打印该单词。 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 python-3.x


    【解决方案1】:
    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'
    

    【讨论】:

      【解决方案2】:

      您可以将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
      

      或者按照 jon clements 的建议使用 try/except:

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

      【讨论】:

      • Python 3.4 有一个default keyword argument,当可迭代对象为空时返回。
      • @kroolik 是的,没有看到 python3 标签
      • 你最好使用try: return max(splitlist.split(), key=len)except ValueError: return '' 没有单词在我看来是个例外 - 因为.split() 默认情况下会自动处理剥离和多个拆分分隔符...(if splitlist.strip() 似乎有点浪费)
      • @JonClements, maxword(""),maxword(" ") 将在 python2 中抛出错误。我只是想添加一个简单简洁的方法来捕获类似于 python3 版本的那些情况。我不认为 OP 真的在检查空字符串,我只是为了完整性而添加了它,但肯定 try/except 可能是更好的方法。
      • @Padraic 我想说的是,this 这样的东西可以在 2.5+ 的任何版本中使用,并且不会明确地检查 empty 字符串的特殊情况(加上 - 我认为您的 3.x 版本已损坏,因为它会将单词列表的长度与单个字符进行比较)
      【解决方案3】:

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

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

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

      【讨论】:

      • 感谢您的回答。这正是我卡住的地方。我知道我想做什么,只是不知道如何实现它。寻求帮助是我最后的手段。
      【解决方案4】:

      你可以使用 heapq 模块中的 nlargest

      import heapq
      heapq.nlargest(1, sentence.split(), key=len)
      

      【讨论】:

        【解决方案5】:
        sentence = raw_input("Enter sentence: ")
        words = sentence.split(" ")
        maxlen = 0
        longest_word = ''
        for word in words:
            if len(word) > maxlen:
                  maxlen = len(word)
                  longest_word = word
        print(word, maxlen)
        

        【讨论】:

          猜你喜欢
          • 2021-05-09
          • 2016-06-10
          • 2013-02-12
          • 1970-01-01
          • 1970-01-01
          • 2019-04-27
          • 2020-02-04
          • 2016-02-04
          相关资源
          最近更新 更多