我正在处理一些编造的代码以尝试理解 *args
功能,但我很难让我的 counter
变量不被重置。
在第 4 个项目之后,编号重置回 0,但我希望它在整个 args 中继续。
lst = ['apple', 'banana', 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']
def generateMenu(*args):
counter = 0
for i in args:
def recurse(l, counter):
for i in l:
counter += 1
if isinstance(i, (list, tuple)):
recurse(i, counter)
else:
print("{}. {}.".format(counter, i))
recurse(i, counter)
generateMenu(lst, lst2, lst3)
输出:
1. apple.
2. banana.
3. orange.
4. lemon.
1. apple2.
2. banana2.
3. orange2.
4. lemon2.
1. apple3.
2. banana3.
3. orange3.
4. lemon3.
你应该让counter
成为一个nonlocal
(nonlocal是在Python3中引入的)
lst = ['apple', 'banana', 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']
def generateMenu(*args):
counter = 0
for i in args:
def recurse(l):
nonlocal counter
for i in l:
counter += 1
if isinstance(i, (list, tuple)):
recurse(i)
else:
print("{}. {}.".format(counter, i))
recurse(i)
generateMenu(lst, lst2, lst3)
或者,从 recurse
返回 counter
lst = ['apple', 'banana', 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']
def generateMenu(*args):
counter = 0
for i in args:
def recurse(l, counter):
for i in l:
counter += 1
if isinstance(i, (list, tuple)):
counter = recurse(i, counter)
else:
print("{}. {}.".format(counter, i))
return counter
counter = recurse(i, counter)
generateMenu(lst, lst2, lst3)
我是一名优秀的程序员,十分优秀!