从列表和字典中创建新元组

时间:2017-07-04 04:57:55

标签: python numpy dictionary tuples

我试图通过将字典键和一个numpy数组拼接成一个列表来拼接一个新的元组。但是,我收到此错误

TypeError: list indices must be integers, not tuple

这是我的代码

import numpy
import random


print(ly) 
{(1, 3): 2, (5, 2): 1, (10, 1): 0}

def myFun(layout):
    possibilities = numpy.zeros(shape=(4,2))
    possibilities[0] = [1, 0]
    possibilities[1] = [-1, 0]
    possibilities[2] = [0, 1]
    possibilities[3] = [0, -1]

    newLayout = tuple()
    for i in layout:
        randomDirection = random.choice( possibilities )
        newLayout = newLayout + layout.keys()[i] + list(randomDirection)
解释器显示此行

newLayout = newLayout + layout.keys()[i] + list(randomDirection)

有问题,但我不明白为什么

1 个答案:

答案 0 :(得分:3)

而不是代码newLayout = newLayout + layout.keys()[i] + list(randomDirection)

使用以下, newLayout = newLayout + layout[i] + list(randomDirection)

将解决您的问题