【问题标题】:Iterate over a list of dictionaries to get certain value if other value has a certain property如果其他值具有特定属性,则遍历字典列表以获得特定值
【发布时间】:2021-02-08 17:48:41
【问题描述】:

我“解码”了一本字典并归结为:

waycategory_values = data['features'][0]['properties']['extras']['waycategory']['summary']

导致:

[{'value': 3.0, 'distance': 230472.2, 'amount': 96.03}, {'value': 0.0, 'distance': 8713.7, 'amount': 3.63}, {'value': 1.0, 'distance': 811.1, 'amount': 0.34}]

现在我想获取距离并将相应的值相加,如果值 = 1.0、2.0 或 3.0 我尝试通过执行以下操作来获取距离:

for distance in waycategory_values[0:]['distance']:
    if waycategory_values[0:]['value'] == 1.0 or 2.0 or 3.0:
        print(distance)

嗯 - 这显然是错误的.. 但似乎无法弄清楚如何去做 - 如果你能给我一个提示,那就太棒了!

【问题讨论】:

标签: python list loops dictionary


【解决方案1】:
data = [{'value': 3.0, 'distance': 230472.2, 'amount': 96.03}, {'value': 0.0, 'distance': 8713.7, 'amount': 3.63}, {'value': 1.0, 'distance': 811.1, 'amount': 0.34}]

total_distance = 0
# just go through the list, no need for indexing
for dataset in data:
    if dataset['value'] in [1.0, 2.0, 3.0]: # <- list of values to check against
        total_distance += dataset['distance']

【讨论】:

    【解决方案2】:
    d=[{'value': 3.0, 'distance': 230472.2, 'amount': 96.03}, {'value': 0.0, 'distance': 8713.7, 'amount': 3.63}, {'value': 1.0, 'distance': 811.1, 'amount': 0.34}]
    sum(v['distance'] for v in d if v['value'] == 1 or v['value'] == 2 or   v['value'] ==  3  )
    
    231283.30000000002  
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2021-12-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多