【问题标题】:I want to make a function that takes a sentence and returns a list the longest word along with words that have the same length of the longest word我想制作一个函数,它接受一个句子并返回一个最长单词列表以及与最长单词长度相同的单词
【发布时间】:2020-11-12 08:03:30
【问题描述】:

下面的代码只是将字符串拆分成一个列表,并选择列表中最长的单词。但现在我也想附加最长单词长度相同的单词。例如,如果输入是“me dog cat”,则输出应该是 ['dog', 'cat']。

def longest_wordlist(string):
    string = string.split()
    longest = ''
    for i in range(len(string)):
        if len(string[i]) > len(string[i-1]):
            longest = string[i]
    return longest

【问题讨论】:

    标签: python list


    【解决方案1】:

    你可以使用多个 if 条件首先检查更长的情况,第二个是相同的长度

    def longest_wordlist(string):
        string = string.split()
        longest = []
        longest_length = 0
        for i in range(len(string)):
            if len(string[i]) > longest_length:
                longest = [string[i]]
                longest_length = len(string[i])
            elif len(string[i]) == longest_length:
                longest.append(string[i])
        return longest
    

    结果

    >>> longest_wordlist("me dog cat")
    ['dog', 'cat']
    

    【讨论】:

      【解决方案2】:

      你也可以不使用范围函数做同样的事情。

      def longest_wordlist(string):
          string = string.split()
          longest = []
          longest_length = 0
          for word in string:
              if len(word)>longest_length:
                  longest_length=len(word)
                  longest=[word]
              elif len(word)==longest_length:
                  longest.append(word)
          return longest
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-03-05
        • 1970-01-01
        • 2021-12-29
        • 2012-02-02
        • 1970-01-01
        • 2013-01-16
        • 2022-01-01
        相关资源
        最近更新 更多