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

别说谁变了你拦得住时间么 提交于 2021-02-08 09:53:41

问题


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)

When I call list 'wordlist' it returns that there isn't anything inside the list. How do I get the list to be callable outside of the function since it works inside the function.

EDIT: Thank you I have updated the code to reflect the mistake I was making using a print tag instead of a return tag.


回答1:


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)

Just add return wordlist to the function. Adding a return statement in a function returns the object whenever the function is called appropriately and you can store that returned variable in a global scope variable.




回答2:


You can use the list that first function creates as an argument for the second function:

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())

You can use this in the future as reference.



来源:https://stackoverflow.com/questions/46259013/how-do-i-call-a-list-outside-of-a-function-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!