使用 dict 数据类型创建嵌套循环

creating nested loop with dict data type

我是 运行 一个循环来计算 abs(x-y) 进行 n 次试验

我的代码:

for i in P0:
     answer = (i['x']-i['y'])
     A = (abs(answer))

returns P0

的值

P0是第一个试验的位置数据(P0 = T0['positions'])。

有没有一种方法可以使用嵌套循环遍历所有路径 (Tn) 的所有位置 (Pn)?

T type - list, of all the trails  
Tn type - dict of the 1st trial 

P type - list, of the positions (x,y) coordinates
Pn type - list

我试过了:

for i in T:
       Ti = T[i]
       Pi = Ti['positions']
       for i in Pi: 
             answer = (i['x']-i['y'])
             A = (abs(answer))

但我收到错误:

TypeError: list indices must be integers or slices, not dict.

我不熟悉 dict 数据类型,有没有什么办法可以让这个工作正常进行

谢谢

在您的情况下 i(第一个)实际上是您要搜索的 Ti。试试这个:

for Ti in T:
   Pi = Ti['positions']
   for i in Pi: 
       answer = (i['x']-i['y'])
       A = (abs(answer))

我给出了一个详细的解决方案,虽然效率低下但很有趣,但对理解字典的工作原理有一定帮助。

abc_1 = {"ball":100, "bat":200}
abc_2 = {"green":10, "red":20}

key_1 = list(abc_1.keys())
key_2 = list(abc_2.keys())


for i in range (len(key_1)):
    print(abc_1[([key_1][0][i])] - abc_2[([key_2][0][i])])

输出为:

90
180