Python:在列表中查找最长/最短的单词并在函数中调用它们

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26132770/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:08:19  来源:igfitidea点击:

Python: Finding Longest/Shortest Words In a List and Calling Them in a Function

pythonfunctionloopsfor-loopmaps

提问by Shayd3

I have a list of words: words=["alpha","omega","up","down","over","under","purple","red","blue","green"] I have two functions that are supposed to find the shortest and longest words in this list:

我有一个单词列表: 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)

I have these functions nested so I can call them all at once:

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

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()

This is just returning this without inputing the words in the list:

这只是在不输入列表中的单词的情况下返回此内容:

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: .

Not sure why, any help is appreciated.

不知道为什么,任何帮助表示赞赏。

回答by wasserfeder

First, you have an error in the code of function bigWords. You should compare with the length and not the word as follows

首先,您在 function 的代码中有错误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

Second, to use the two functions, you need to call them for the list of words and not for each word:

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

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()

回答by John1024

If you like, there are simpler ways to approach the problem:

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

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],)

This produces:

这产生:

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.

回答by theideasmith

You are so close - but I think the problem is incallFunctions(). You are mapping the functions in func_list2to every stringin the words array, not applying the function to the array as a whole. It was a good idea to use map, which is a powerful function, but you don't need to use it here. Here is code that I tested with a simple online interpreter. Try it. Good luck with whatever you are learning/ the project you are making!

你是如此接近 - 但我认为问题出在callFunctions(). 您将函数映射func_list2到words 数组中的每个字符串,而不是将函数作为一个整体应用于数组。使用 map 是个好主意,这是一个强大的功能,但您不需要在这里使用它。这是我用一个简单的在线解释器测试的代码。尝试一下。祝你学习/正在做的项目好运!

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()

回答by Ankit Sharma

Just use max and min functions having key as the length

只需使用以 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)

回答by 2RMalinowski

Try this simple solution:

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

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

回答by Tal hodorkovsky

you can sort you list using sorted()function that allows you to sort the list by the length of the strings in it.for that you need to add key=lenso the function will sort by length and not by alphabecit order. you also need to give to the function reverse=true so it will be easier to access to the longest string (it will be in [0] at the list)

您可以使用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))

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))

回答by harish joshi

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))

try calling :longestWord(['longerthanlongest','long','longer','longest'])

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

same thing can be done to find the samllest.

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