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

Python 使用dict数据类型创建嵌套循环,python,numpy,for-loop,statistics,nested-loops,Python,Numpy,For Loop,Statistics,Nested Loops,我正在运行一个循环来计算abs(x-y)的n试验 我的代码: for i in P0: answer = (i['x']-i['y']) A = (abs(answer)) 返回P0 P0是第一次试验的位置数据(P0=T0['positions']) 是否有一种方法可以使用嵌套循环在所有轨迹(Tn)的所有位置(Pn)循环 T type - list, of all the trails Tn type - dict of the 1st trial P type -

我正在运行一个循环来计算
abs(x-y)
n
试验

我的代码:

for i in P0:
     answer = (i['x']-i['y'])
     A = (abs(answer))
返回
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

您想要什么还不是很清楚,您能提供样本数据吗?