【问题标题】:making new tuple from list and dictionary从列表和字典中创建新元组
【发布时间】:2017-07-04 04:57:54
【问题描述】:

我试图通过将一个字典键和一个 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)

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

【问题讨论】:

  • 我假设lylayout 的形式传入。 ly 的键是元组,所以for i in layout 意味着ituple,你不能用tuple 索引list。注意:Py3 中的layout.keys() 不再返回list,即使iint 也会中断。
  • 你的字典键是元组,你正在循环它们,所以i的类型肯定是tuple
  • 您能否分享所需的输出。

标签: python numpy dictionary tuples


【解决方案1】:

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

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

会解决你的问题

【讨论】:

  • 从声明中删除.keys()
  • 我尝试了您的建议,但收到以下错误“TypeError: can only concatenate tuple (not "int") to tuple”
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
  • 2014-12-18
  • 2021-08-14
  • 2015-07-15
相关资源
最近更新 更多