在函数Python之间传递列表 [英] Passing a list between functions Python
问题描述
如果我在一个函数中创建列表并进行编辑,那么我希望能够将完成的列表传递给另一个函数,在该函数中它将用于执行更多操作.
If I make a list in one function, and edit it, then I want to be able to pass the finished list off to another function where it will be used to do more things.
def func1():
numbers = [1, 2, 3, 4]
if numbers.count(1) > 0:
numbers.remove(1)
func2()
def func2():
two = numbers[0]
func1()
如何获取它,以便它不会提取未全局定义的错误号.我知道为什么会导致错误,但是经过研究,我仍然找不到解决此问题的好方法.
How could I get it so that it doesn't pull the error numbers not defined globally. I know why it is pulling the error, but after researching, I still can't find a good way to fix this problem.
推荐答案
根据您的里程和要求,选择一个
Based on your mileage and requirement, choose one
-
将列表作为参数传递给被调用的函数
Pass the list as a parameter to the called function
def func2(numbers):
two = numbers[0]
def func1():
numbers = [1, 2, 3, 4]
if numbers.count(1) > 0:
numbers.remove(1)
func2(numbers)
使两个类的功能都成为一个类的一部分,并使列表成为实例属性
Make both the functions part of a single Class and make the list an instance attribute
class Foo(object):
def __init__(self, numbers):
self.numbers = numbers
pass
def func1(self):
if self.numbers.count(1) > 0:
self.numbers.remove(1)
self.func2()
def func2(self):
two = self.numbers[0]
Foo([1, 2, 3, 4]).func1()
重新设计,以便调用方装饰被调用的函数
Redesign so that the called function is decorated with the caller
def func1(func):
def wraps(*argv):
numbers = argv[0]
if numbers.count(1) > 0:
numbers.remove(1)
func(*argv)
return wraps
@func1
def func2(numbers):
two = numbers[0]
func2([1,2,3,4])
使用嵌套函数关闭
Closure with nested function
def func1():
def func2():
two = numbers[0]
numbers = [1, 2, 3, 4]
if numbers.count(1) > 0:
numbers.remove(1)
func2()
func1()
这篇关于在函数Python之间传递列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!