【问题标题】:Extracting dictionary values in for loop to fill list在for循环中提取字典值以填充列表
【发布时间】:2019-01-29 18:24:46
【问题描述】:

我有这个代码:

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = np.where(result['depth'] ==  v)
    values_v = [result[string][temp_v] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))

我想在其中创建一个名为“this_v”的新dict,其键与原始字典result 相同,但值更少。

行:

values_v = [result[string][temp_v] for string in result.keys()]

报错

TypeError:列表索引必须是整数,而不是元组

我不明白,因为我可以创建 ex = result[result.keys()[0]][temp_v] 就好了。它只是不允许我使用 for 循环来执行此操作,以便我可以填充列表。

知道为什么它不起作用吗?

【问题讨论】:

  • np.where 返回一个元组

标签: python numpy dictionary


【解决方案1】:

我不确定您要达到什么目的,但我可以解决您的问题:

np.where 正在返回一个元组,因此要访问您需要提供索引 temp_v[0]。此外,元组的值是一个数组,因此要遍历该值,您需要运行另一个循环 a for a in temp_v[0],它可以帮助您访问该值。

import numpy as np

result = {}
result['depth'] = [1,1,1,2,2,2]
result['generation'] = [1,1,1,2,2,2]
result['dimension'] = [1,2,3,1,2,3]
result['data'] = [np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0]), np.array([0,0,0])]

for v in np.unique(result['depth']):
    temp_v = np.where(result['depth'] ==  v)
    values_v = [result[string][a] for a in temp_v[0] for string in result.keys()]
    this_v = dict(zip(result.keys(), values_v))

【讨论】:

  • 嘿,谢谢。实际上,我通过使用口罩找到了更好的方法。现在我有 temp_v = (result['depth'] == v) values_v = [result[string][temp_v] for string in result.keys()] 但它仍然给出错误,“只有整数标量数组可以转换为标量索引"
  • 试试这行values_v = [result[string][a] for a in temp_v[0] for string in result.keys()]
  • 这行得通,但我正在尝试减少 for 循环的数量。因此,掩蔽的想法
  • 你能在问题中编辑你的代码吗,然后我可以帮你
猜你喜欢
  • 2021-07-06
  • 1970-01-01
  • 2016-11-25
  • 2020-05-30
  • 1970-01-01
  • 1970-01-01
  • 2016-02-23
  • 2012-09-27
相关资源
最近更新 更多