簡體   English   中英

Python,While-True循環,該循環獲取整數並返回相同長度的單詞

[英]Python, While-True loop that gets an integer and returns a word with same length

我不確定如何開始此功能。 從概念上講,我認為它應該遍歷單詞列表,直到找到長度與給定整數相同的單詞,然后再返回該單詞。

lenword(num)的示例

def lenword(4):
   wrdlst = [ 'i' , 'to', 'two', 'four']
while True:
#stuck here

#returns 'four'

請幫忙!

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 

您可能想要這樣的東西:

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'

如果您的列表按順序排列,使得第n個元素的長度為n + 1,那么您可以:

wrdlist = [ 'i' , 'to', 'two', 'four']

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

lenword(4)
def lenword(n, words):
    for word in words:
        if len(word) == n:
            return word

>>> wrdlst = [ 'i' , 'to', 'two', 'four']
>>> lenword(4, wrdlst)
'four'

首先,您的功能定義已關閉。 定義函數時,請為參數選擇一個名稱,然后在調用函數時傳遞值4

def lenword(length):
    wrdlst = ['i', 'to', 'two', 'for']
    for word in wrdlst:
        if len(word) == length:
            return word
    return None

然后您將調用此函數,例如:

print lenword(4)

首先,您必須像以前一樣定義單詞列表。 下一步是了解您需要學習的概念,例如字符串的長度和循環。

所以它應該看起來像這樣:

def lenword(word_length):
    wrdlst = [ 'i' , 'to', 'two', 'four']
    for word in wrdlist:
        if len(word) == word_length:
            return word

您可以通過將字符串數組作為函數的參數來改進此功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM