Python:在列表中查找最长/最短的单词并在函数中调用它们 [英] Python: Finding Longest/Shortest Words In a List and Calling Them in a Function
本文介绍了Python:在列表中查找最长/最短的单词并在函数中调用它们的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个单词列表: words = ["alpha","omega","up","down","over","under","purple","red","blue","green"] 我有两个函数应该在此列表中找到最短和最长的单词:
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:
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.
推荐答案
如果愿意,可以使用更简单的方法来解决该问题:
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],)
这将产生:
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.
这篇关于Python:在列表中查找最长/最短的单词并在函数中调用它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文