gpt4 book ai didi

python - 遍历 *args 重置计数器

转载 作者:太空宇宙 更新时间:2023-11-04 10:00:09 25 4
gpt4 key购买 nike

我正在处理一些编造的代码以尝试理解 *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)

关于python - 遍历 *args 重置计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43970327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com