python - 如何索引子字典并创建嵌套 for 循环

标签 python dictionary for-loop indexing

我有一个列表列表,如下所示:

>> new_pd[:3]
[['PokedexNumber',
  'Name',
  'Type',
  'Total',
  'HP',
  'Attack',
  'Defense',
  'SpecialAttack',
  'SpecialDefense',
  'Speed'],
 [1.0, 'Bulbasaur', 'GrassPoison', 318.0, 45.0, 49.0, 49.0, 65.0, 65.0, 45.0],
 [2.0, 'Ivysaur', 'GrassPoison', 405.0, 60.0, 62.0, 63.0, 80.0, 80.0, 60.0]]

我要创建的内容如下:

{1.0: {'Attack': 49.0,
  'Defense': 49.0,
  'HP': 45.0,
  'Name': 'Bulbasaur',
  'PokedexNumber': 1.0,
  'SpecialAttack': 65.0,
  'SpecialDefense': 65.0,
  'Speed': 45.0,
  'Total': 318.0,
  'Type': 'GrassPoison'},
 2.0: {'Attack': 62.0,
  'Defense': 63.0,
  'HP': 60.0,
  'Name': 'Ivysaur',

所以从列表的列表中,我想要一个大的嵌套字典。

为了创建它,我用 Python 编写了以下代码:

new_pd_keys = []
for i in range(1, len(new_pd)):
    new_pd_keys.append(new_pd[i][0]) 

在上面,我从第 1 列中获取所有 key 并将它们保存到名为 new_pd_keys 的列表中。

然后使用下面的代码为每个键分配值:

for i in range(1,len(new_pd)):
    new_pd_dict = {key:{'Attack':new_pd[i][5], 'Defense':new_pd[i][6], 'HP':new_pd[i][4], 
          'Name':new_pd[i][1], 'PokedexNumber':new_pd[i][0], 'SpecialAttack':new_pd[i][7],
          'SpecialDefense':new_pd[i][8], 'Speed':new_pd[i][9], 'Total':new_pd[i][3], 
          'Type':new_pd[i][2]} for key in new_pd_keys }

但我拥有的是最后一行的属性。你可以看到下面的输出,都是一样的。

{1.0: {'Attack': 110.0,
  'Defense': 120.0,
  'HP': 80.0,
  'Name': 'Volcanion',
  'PokedexNumber': 721.0,
  'SpecialAttack': 130.0,
  'SpecialDefense': 90.0,
  'Speed': 70.0,
  'Total': 600.0,
  'Type': 'FireWater'},
 2.0: {'Attack': 110.0,
  'Defense': 120.0,
  'HP': 80.0,
  'Name': 'Volcanion',
  'PokedexNumber': 721.0,
  'SpecialAttack': 130.0,
  'SpecialDefense': 90.0,
  'Speed': 70.0,
  'Total': 600.0,
  'Type': 'FireWater'},

你能建议一种比我的更好的索引编制方法吗?

最佳答案

new_thing = {q[0]: dict(zip(thing[0], q[1:])) for q in thing[1:]}

关于python - 如何索引子字典并创建嵌套 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53253616/

相关文章:

python - 使用 sqlalchemy 进行 bool 字段查询

python - 寻找物体中心: showing wrong coordinate outside of the target object

Scala 案例类映射扩展

java - 看似无限循环终止,除非使用 System.out.println

c++ - 使用 for 循环是否比在 C++ 中将内容保存在 vector 中更快?

python - 使用 Python 将 JSON 转换为 CSV 问题

python - Numpy,为什么 `x += y` 产生的结果与 `x = x + y` 不同?

javascript - 如何在 Mapbox.js 中的两个坐标之间的直线上移动标记

c#dictionary<string,string> order by key asc 最后为空值

c# - 从变量更改 if 语句