dict.pop上的Python3类型错误

时间:2015-11-19 21:25:18

标签: python dictionary python-3.5

我试图反映一个对称群的所有排列的平方。 方块的“坐标”用作字典中的键。价值 现在应该沿x轴反射。但出于某种原因 .pop()只想接受整数?我认为它接受任何不包含immutables的类型,如果一个键不在字典中,则会引发KeyError。这是我的代码:

def y_reflection(insquare):
    """Function that reflects a square against it's y axis:
                <----- reflection

                            --> x
    n   n-1 ... 2 1 |   1 2 ... n-1 n
    n-1 n-2 ... 1 n | | n 1 ... n-2 n-1
    ............... | v ................
    2   1   ... 4 3 | y 3 4 ... 1   2 
    1   n   ... 3 2 |   2 3 ... n   1"""

    for y in range (0, SQUARE_SIZE()):
        for x in range (0, SQUARE_SIZE()):
            insquare[(y,x)]=insquare.pop((y,(SQUARE_SIZE()-x)))
    return insquare

    insquare[(x,y)]=insquare.pop((x,(SQUARE_SIZE()-y)))
TypeError: 'tuple' object cannot be interpreted as an integer

知道发生了什么事吗?

3 个答案:

答案 0 :(得分:1)

您绝对确定insquaredict吗?如果insquarelist,则会出现错误。

旁注:您已在此代码中重新计算SQUARE_SIZE();一次针对外部range(不是问题),然后针对内部SQUARE_SIZE() range次,然后针对内部循环体SQUARE_SIZE() ** 2次。即使SQUARE_SIZE()返回一个常量值,简单地调用一个函数的开销也可能是运行时的一个主要因素。如果SQUARE_SIZE()有副作用,那么您需要经常调用它们。为了避免大量不必要的range创建,SQUARE_SIZE()调用以及不需要循环,您可能需要import itertools并在函数中更改为类似的内容:

sqsize = SQUARE_SIZE()
for y, x in itertools.product(range(sqsize), repeat=2):
    # I removed a bunch of unnecessary parens here as well
    insquare[y, x]=insquare.pop((y, sqsize - x))
return insquare

答案 1 :(得分:0)

我已经测试了你的代码。该错误不在该函数内部。错误是您定义insquare的位置。从错误的外观来看,您需要检查是否要传递字典。我尝试使用下面的代码,它完美无缺。

def y_reflection(insquare):
    """Function that reflects a square against it's y axis:
                <----- reflection

                            --> x
    n   n-1 ... 2 1 |   1 2 ... n-1 n
    n-1 n-2 ... 1 n | | n 1 ... n-2 n-1
    ............... | v ................
    2   1   ... 4 3 | y 3 4 ... 1   2 
    1   n   ... 3 2 |   2 3 ... n   1"""

    for y in range (0, 1):
        for x in range (0, 1):
            insquare[(y,x)]=insquare.pop((y,(1-x)))
    return insquare

    insquare[(x,y)]=insquare.pop((x,(1-y)))

d = {
        (0,0): 0,
        (0,1): 1,
        (1,0): 1,
        (1,1): 0
    }
print (y_reflection(d))

测试链接 - https://repl.it/B1kZ/1

答案 2 :(得分:-1)

我认为错误在:

insquare[(x,y)]

这:(x,y)是一个元组。