首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,While-True循环,获取整数并返回相同长度的单词

Python,While-True循环,获取整数并返回相同长度的单词
EN

Stack Overflow用户
提问于 2015-03-11 22:49:32
回答 6查看 110关注 0票数 0

我不确定如何开始这个函数。从概念上讲,我认为它应该查找单词列表,直到找到与给定整数长度相同的单词,才返回该单词。

lenword(num)示例

代码语言:javascript
复制
def lenword(4):
   wrdlst = [ 'i' , 'to', 'two', 'four']
while True:
#stuck here

#returns 'four'

请帮帮我!

EN

回答 6

Stack Overflow用户

发布于 2015-03-11 22:52:51

代码语言:javascript
复制
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)

或者如果你的列表中有一个以上的四个字母的单词。

代码语言:javascript
复制
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 
票数 3
EN

Stack Overflow用户

发布于 2015-03-11 22:51:47

你可能想要这样的东西:

代码语言:javascript
复制
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

使用为特定的单词列表创建专门的搜索器可以使其更好:

代码语言:javascript
复制
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

并像这样使用它:

代码语言:javascript
复制
# 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'
票数 2
EN

Stack Overflow用户

发布于 2015-03-11 22:52:08

如果你的列表是有序的,这样第n个元素的长度是n+1,那么你只需要:

代码语言:javascript
复制
wrdlist = [ 'i' , 'to', 'two', 'four']

def lenword(n):
   return wrdlist[n-1]

lenword(4)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28989806

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档