多次调用时函数的独立变量

Independant Variable for Function when called Multiple Times

我正在尝试创建一个函数来打印列表中的元素。但是,我想要它以便每次在 If 语句中使用该函数时我都可以打印下一个元素。这是我得到的:

import random

index = 0
list1 = ['one', 'two', 'three', 'four', 'five', ]
list2 = ['uno', 'dos', 'tres', 'cuatro', 'cinco', ]

def reshuffle(list):
    global index
    if index < len(list):
        print(list[index])
        index += 1
    elif index == len(list):
        random.shuffle(list)
        index = 0
        print(list[index])
        index += 1

while True:
    user_input = input("Enter command: ")
    if user_input == "e":
        print(reshuffle(list=list1))
    if user_input == "s":
        print(reshuffle(list=list2))

每当函数使用 if 语句打印出列表中的所有元素时,它会打乱它们并重新开始。它通过使用索引来实现这一点,但每次该函数被多个 if 语句使用时,它都会读取同一个变量。输出如下所示:

Enter command: e
one
None
Enter command: e
two
None
Enter command: s
tres
None
Enter command: s
cuatro
None

我希望它这样做:

Enter command: e
one
None
Enter command: e
two
None
Enter command: s
uno
None
Enter command: s
dos
None

如何让每个函数调用独立使用同一个变量,而不重置变量?或者,如果有另一种方法可以解决这个问题,我们将不胜感激。

您的列表共享同一个全局 index,因此一个列表的索引更改自然会影响另一个列表。

您应该创建一个 list 的子 class,将 index 作为实例变量,使 reshuffle 成为 class 的方法,并使list1list2 个 class 的实例,以便它们每个都可以跟踪自己的索引:

import random

class List(list):
    def __init__(self, *args):
        super().__init__(*args)
        self.index = 0

    def reshuffle(self):
        if self.index < len(self):
            print(self[self.index])
            self.index += 1
        elif self.index == len(self):
            random.shuffle(self)
            self.index = 0
            print(self[self.index])
            self.index += 1

list1 = List(['one', 'two', 'three', 'four', 'five'])
list2 = List(['uno', 'dos', 'tres', 'cuatro', 'cinco'])

while True:
    user_input = input("Enter command: ")
    if user_input == "e":
        print(list1.reshuffle())
    if user_input == "s":
        print(list2.reshuffle())

样本input/output:

Enter command: e
one
None
Enter command: e
two
None
Enter command: s
uno
None
Enter command: s
dos
None