【问题标题】:creating nested loop with dict data type使用 dict 数据类型创建嵌套循环
【发布时间】:2020-11-26 13:53:49
【问题描述】:

我正在运行一个循环来计算 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 数据类型,有什么方法可以完成这项工作

谢谢

【问题讨论】:

  • 不是很清楚你想要什么,能否提供样本数据?

标签: python numpy for-loop statistics nested-loops


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我给出了一个低效且有趣的详细解决方案,但它有助于理解字典的工作原理。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-15
      • 1970-01-01
      • 2019-07-21
      • 1970-01-01
      • 2012-07-24
      • 2018-03-31
      • 1970-01-01
      • 2016-05-09
      相关资源
      最近更新 更多