【问题标题】:Python: Finding Longest/Shortest Words In a List and Calling Them in a FunctionPython:在列表中查找最长/最短的单词并在函数中调用它们
【发布时间】:2014-10-01 01:30:13
【问题描述】:

我有一个单词列表: words=["alpha","omega","up","down","over","under","purple","re​​d","blue","green"] 我有两个函数可以在这个列表中找到最短和最长的单词:

def bigWords(list=[], *args):
    largestWord=""
    largestLen=0
    for word in list:
        if largestWord<len(word):
            largestWord=len(word)
            largestWord=word
    print "The longest word(s) in the list is %s." % largestWord

def smallWords(list=[], *args):
    smallestWord=""
    smallestLen=0
    for word in list:
        if smallestLen>len(word):
            smallestLen>len(word)
            smallestWord=word
    print "The shortest word(s) in the list is: %s." % (smallestWord)

我有这些函数嵌套,所以我可以一次调用它们:

def callFunctions():
###Words###
    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]

    wordLength=lenList(words)
    print "The amount of words[] is %d" % wordLength
    func_list2 = [bigWords, smallWords]
    for f in func_list2:
        map(f, words)

callFunctions()

这只是返回这个而不输入列表中的单词:

The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The longest word(s) in the list is .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .
The shortest word(s) in the list is: .

不知道为什么,感谢任何帮助。

【问题讨论】:

    标签: python function loops for-loop maps


    【解决方案1】:

    如果你愿意,还有更简单的方法来解决这个问题:

    words=["alpha","omega","up","down","over","under","purple","red","blue","green"]
    sortedwords = sorted(words, key=len)
    print "The number of words in the list is: %s." % (len(words),)
    print "The shortest word in the list is: %s." % (sortedwords[0],)
    print "The longest word in the list is: %s." % (sortedwords[-1],)
    

    这会产生:

    The number of words in the list is: 10.
    The shortest word in the list is: up.
    The longest word in the list is: purple.
    

    【讨论】:

      【解决方案2】:

      只需使用以 key 为长度的 max 和 min 函数

      y = []
      for names in range(4):
         name = raw_input('Enter:')
         y += name,
      s = max(y, key=len)
      r = min(y, key=len)
      

      【讨论】:

        【解决方案3】:

        你是如此接近 - 但我认为问题出在callFunctions()。您将 func_list2 中的函数映射到 words 数组中的每个 string,而不是将函数应用到 整个数组。使用 map 是个好主意,这是一个强大的功能,但您不需要在这里使用它。这是我用simple online interpreter 测试的代码。尝试一下。祝你所学/正在做的项目一切顺利!

        def bigWords(list=[], *args):
            largestWord=""
            for word in list:       
                if len(largestWord)<len(word):
                    largestWord= word
            print "The longest word(s) in the list is %s." % largestWord
            return largestWord
        
        def smallWords(list=[], *args):
            smallestWord = bigWords(list)
            for word in list:
                if len(smallestWord)> len(word):
                    smallestWord = word
            print "The shortest word(s) in the list is: %s." % (smallestWord)
        
        
        def callFunctions():
        ###Words###
            words=["alpha","omega","up","down","over","under","purple","red","blue","green"]
        
            wordLength=len(words)
            print "The amount of words[] is %d" % wordLength
            func_list2 = [bigWords, smallWords]
            for f in func_list2:
                f(words)
        
        callFunctions()
        

        【讨论】:

          【解决方案4】:

          首先,函数bigWords的代码有错误。你应该比较长度而不是单词如下

          def bigWords(list=[], *args):
              largestWord=""
              largestLen=0
              for word in list:
                  if largestLen<len(word):
                      largestLen=len(word)
                      largestWord=word
              print "The longest word(s) in the list is %s." % largestWord
          

          其次,要使用这两个函数,您需要为单词列表而不是每个单词调用它们:

          def callFunctions():
          ###Words###
              words=["alpha","omega","up","down","over","under","purple","red","blue","green"]
          
             wordLength=lenList(words)
             print "The amount of words[] is %d" % wordLength
             func_list2 = [bigWords, smallWords]
             for f in func_list2:
                 f(words)
          
          callFunctions()
          

          【讨论】:

          • 我将如何找到最小的单词?我的输出一直给我“e”作为最小的单词。
          • @Shayd3 你在那个函数中也有一个错误。用 minimumLen=len(word) 替换 if 块中的第一行。
          【解决方案5】:

          试试这个简单的解决方案:

          def find_longest_and_shortest_word(list_of_words):
              longest_word = list_of_words[0]
              shortest_word = list_of_words[0]
              for word in list_of_words:
                  if len(longest_word) < len(word):
                      longest_word = word
                  if len(shortest_word) > len(word):
                      shortest_word = word
              print(f'The longest word is: {longest_word}')
              print(f'The shortest word is: {shortest_word}')
              return longest_word, shortest_word
          

          【讨论】:

            【解决方案6】:

            您可以使用sorted() 函数对列表进行排序,该函数允许您按其中字符串的长度对列表进行排序。为此,您需要添加key=len,因此该函数将按长度排序,而不是按字母顺序排序.你还需要给函数 reverse=true 所以访问最长的字符串会更容易(它将在列表的[0]中)

            def longest(my_list): my_list = sorted(my_list, key=len, reverse=True) return my_list[0] list1 = ['aaa', 'bbbb', 'cccccc', 'd'] print(longest(list1))

            【讨论】:

              【解决方案7】:
              def longestWord(words):
              longest=''
              for num in range(len(words)):
                  if len(longest)<len(words[num]):
                      longest=words[num]
              print ('longest word is {}'.format(longest))
              

              尝试调用 :longestWord(['longerthanlongest','long','longer','longest'])

              可以做同样的事情来找到最小的。

              【讨论】:

              • 嘿,哈里什!在回答您的下一个问题之前,请阅读writing an answer!享受您在 SO 的住宿:)
              【解决方案8】:
              words = ["alpha","omega","up","down","over","under","purple","red","blue","green"]
              
              #GET LONGEST WORD
              max(words, key=len)
              >>> 'purple'
              
              #GET SHORTEST WORD
              min(words, key=len)
              >>> 'up'
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2023-03-16
                • 1970-01-01
                • 2013-01-21
                • 1970-01-01
                • 2015-12-11
                相关资源
                最近更新 更多