python函数传递列表,在函数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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值