将变量中的列表替换为不同函数中的其他变量

时间:2016-04-17 12:32:18

标签: python string list python-3.x

我想将列表letters中的元素替换为列表animals中的列表元素,其中print(letters)将打印

["cat","dog","mouse","rabbit","hamster","duck","chicken","goose","hedgehog"]

如何将变量animals的值从函数newlist传递给函数main,然后替换main中的变量值

代码

def newlist():
    animals = ["cat","dog","mouse","rabbit","hamster","duck","chicken","goose","hedgehog"]
def main():
    letters = ["A","B","C","D","E","F","G","H","I"]
    print(letters)
main()  

1 个答案:

答案 0 :(得分:3)

请注意,必须调用Python中的函数并返回特定值,如果未指定任何内容,则返回None

来自Python Tutorial

  

return语句返回一个函数的值。没有表达式参数的return返回None。从函数末尾开始也会返回None

因此,您需要将函数newlist定义为

def newlist():
     animals = ["cat","dog","mouse","rabbit","hamster","duck","chicken","goose","hedgehog"]
     return animals       # RETURN THE LIST

这将按预期返回列表。

要获取列表,您需要调用可以使用newlist()完成的功能。因此,main函数看起来像

def main():
    letters = ["A","B","C","D","E","F","G","H","I"]
    letters = newlist()   # CALL THE FUNCTION 
    print(letters)

现在,当您致电main时,您将获得预期的输出。

您无需使用占位符创建单独的列表。您可以直接致电newlist以使您的清单准备就绪并正常工作。在这种情况下,main函数将减少为

def main():
    letters = newlist()   # newlist returns a list, so call directly 
    print(letters)