Python - 奇怪的列表行为 - 一个变量名,不同的引用?

时间:2017-01-24 21:02:27

标签: python list

我是一名尝试学习Python的Java,C ++,C程序员。在玩一些代码时,我遇到了这种奇怪的行为。我对非静态类型的语言有点熟悉,但不能为这种现象提出解决方案或解释。

ConvertTo-Json

变量或"名称" for i in range(3): div(a,b,c,list) #print(list) list = [] #print(list) printABC(a,b,c) theInput = input("\nselect the column: a, b or c : \n") if "a" in theInput: list = b + a + c elif "b" in theInput: list = a + b + c elif "c" in theInput: list = a + c + b print(list); 是一个数字列表,我将该列表分成另外三个列表(listab)。然后我清除c并使用(listab的预定组合重新填充它。

在循环的第一遍中,c被清除,但是for循环的第二遍list正在引用另一个完全不同的变量,而不是清除list = []

有没有人解释为什么会发生这种情况?

1 个答案:

答案 0 :(得分:0)

就像其中一位已经说过的评论者一样,不要在内置命令之后命名变量。这个Pythoncode应该可以解决这个问题:

a, b, c, = 0, 1, 2
list_1 = [0, 1, 2]
try:
    for i in range(3):   
        a, b, c, = list_1[0], list_1[1], list_1[2]
        print("a:%d, b:%d. c:%d" % (a,b,c))
        theInput = raw_input("\nselect the column: a, b or c : \n")
        if theInput.find("a") > -1:         
            list_1 = [b, a, c]
        elif theInput.find("b") > -1:
            list_1 = [a, b, c]
        elif theInput.find("c") > -1:
            list_1 = [a, c, b]
        print(list_1)
except Exception as e:
    print(e)

try / except块不是必须的,但它在我用作示例的代码中。

相关问题