簡體   English   中英

如何在python中的函數之外調用列表?

[英]How do I call a list outside of a function in python?

def start(B):
    wordlist = []

    for w in B:
        content = w
        words = content.lower().split()
        for each_word in words:

            wordlist.append(each_word)
            print(each_word)
            return(wordlist)

當我調用 list 'wordlist' 時,它返回列表中沒有任何內容。 由於它在函數內部工作,我如何使列表可以在函數外部調用。

在此處輸入圖片說明

編輯:謝謝我更新了代碼以反映我使用打印標簽而不是返回標簽所犯的錯誤。

def start(B):
    wordlist = []

    for w in B:
        content = w
        words = content.lower().split()
        for each_word in words:

            wordlist.append(each_word)
            print(wordlist)
    return wordlist

B=["hello bye poop"]
wordlist=start(B)

只需將return wordlist添加到函數中即可。 在函數中添加return語句會在函數被適當調用時返回對象,並且您可以將該返回的變量存儲在全局范圍變量中。

您可以使用第一個函數創建的列表作為第二個函數的參數:

def some_list_function():
  # generates list
  return mylist

def some_other_function(mylist):
  # takes list as argument and processes
  return result

some_other_function(some_list_function())

您可以在將來使用它作為參考。

暫無
暫無

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

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