我不确定如何开始这个函数。从概念上讲,我认为它应该查找单词列表,直到找到与给定整数长度相同的单词,才返回该单词。
lenword(num)示例
def lenword(4):
wrdlst = [ 'i' , 'to', 'two', 'four']
while True:
#stuck here
#returns 'four'请帮帮我!
发布于 2015-03-11 22:52:51
def lenword(n):
wrdlst = [ 'i' , 'to', 'two', 'four']
# for every item in the list, if the length of that item is
# equal to n (in this case 4) then print the item, and return it.
for word in wrdlst:
if len(word) == n:
print word
return word
# call the function
four_letter_word = lenword(4)或者如果你的列表中有一个以上的四个字母的单词。
def lenword(n):
wrdlst = [ 'i' , 'to', 'two', 'four']
found_words = []
# for every item in the list, if the length of that item is
# equal to n (in this case 4) then print the item, and return it.
for word in wrdlst:
if len(word) == n:
found_words.append(word)
return found_words
# call the function
four_letter_words = lenword(4)
# print your words from the list
for item in four_letter_words:
print item 发布于 2015-03-11 22:51:47
你可能想要这样的东西:
def lenword(word_length):
wordlist = [ 'i' , 'to', 'two', 'four']
for word in wordlist:
if len(word) == word_length:
# found word with matching length
return word
# not found, returns None使用为特定的单词列表创建专门的搜索器可以使其更好:
def create_searcher(words):
def searcher(word_length, words=words):
for word in words:
if len(word) == word_length:
# found word with matching length
return word
# not found, returns None
return searcher并像这样使用它:
# create search function specialized for a list of words
words_searcher = create_searcher(['list', 'of', 'words'])
# use it
words_searcher(4) # returns 'list'
words_searcher(3) # returns None
words_searcher(2) # returns 'of'发布于 2015-03-11 22:52:08
如果你的列表是有序的,这样第n个元素的长度是n+1,那么你只需要:
wrdlist = [ 'i' , 'to', 'two', 'four']
def lenword(n):
return wrdlist[n-1]
lenword(4)https://stackoverflow.com/questions/28989806
复制相似问题