我想将列表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()
答案 0 :(得分:3)
请注意,必须调用Python中的函数并返回特定值,如果未指定任何内容,则返回None
。
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)