循环* args重置计数器

时间:2017-05-15 01:18:13

标签: python python-3.x

我正在编写一些代码来尝试理解*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.

3 个答案:

答案 0 :(得分:2)

你应该让counter成为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)

或者,从counter

返回recurse
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)

答案 1 :(得分:1)

问题是您的recurse功能无法从较高范围了解您的counter。因此,每个for i in l:循环中增加的内容只是“内部”counter变量。

您的示例可能会让您感到困惑,因为您使用了两次相同的变量名称(counteri)。尝试以不同的方式重命名它们,您可能会更好地了解您的代码发生了什么。

答案 2 :(得分:1)

Python对于在函数范围之外写入变量有一些奇怪的规则。避免此IMO的最简单方法是确保递归函数返回每个状态的计数器值。我进行了轻微的重构,使其更加清晰。

lst = [('apple', 'banana'), 'orange', 'lemon']
lst2 = ['apple2', 'banana2', 'orange2', 'lemon2']
lst3 = ['apple3', 'banana3', 'orange3', 'lemon3']


def generateMenu(*args):
    outer_counter = 1

    def recurse(l, inner_counter):
        for i in l:
            if isinstance(i, (list, tuple)):
                inner_counter = recurse(i, inner_counter)
            else:
                print("{}. {}.".format(inner_counter, i))
                inner_counter += 1
        return inner_counter

    for i in args:
        outer_counter = recurse(i, outer_counter)


generateMenu(lst, lst2, lst3)