【问题标题】:How do I call a list outside of a function in python?如何在python中调用函数之外的列表?
【发布时间】:2017-09-16 22:31: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)

当我调用 list 'wordlist' 时,它返回列表中没有任何内容。由于它在函数内部工作,如何让列表在函数外部可调用。

编辑:谢谢我更新了代码以反映我使用打印标签而不是返回标签所犯的错误。

【问题讨论】:

标签: python function call


【解决方案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)

只需在函数中添加return wordlist。在函数中添加return 语句会在适当调用函数时返回对象,并且您可以将返回的变量存储在全局范围变量中。

【讨论】:

  • 非常感谢您。我刚开始学习python,所以不知道该怎么做,而且大多数其他问题似乎都更加复杂,我无法弄清楚我缺少什么来使我的代码正常工作。所以谢谢
【解决方案2】:

您可以使用第一个函数创建的列表作为第二个函数的参数:

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

您可以在将来使用它作为参考。

【讨论】:

  • 谢谢你。我以后会参考这个。不过我很好奇,我是否不需要为每个列表运行这两个函数才能使其工作?那不是更麻烦吗?
  • 规模越大,效率越高
猜你喜欢
  • 2021-03-06
  • 2015-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-21
  • 2014-04-08
  • 2017-02-06
  • 2021-08-24
相关资源
最近更新 更多