簡體   English   中英

Python:遍歷多個字典

[英]Python: Iterating through multiple dictionaries

我有3個列表,每個列表都包含字典。 我將獲取某些鍵的值,並希望保存此值的min-Operation結果。 下面的代碼給出一個錯誤:TypeError:列表索引必須是整數,而不是dict。

import numpy as np
import itertools


humidity = [{'high': 90, 'middle': 50, 'low': 10}, {'high': 75, 'middle': 40, 'low': 5} ]

temperature =[{'warm': 35, 'normal': 20, 'cold': 5 }, {'warm': 40, 'normal': 18, 'cold': 10 }]

wind = [{'breeze': 25, 'gale': 100}, {'breeze': 20, 'gale': 90}]

results=[]
for h, t, w in itertools.izip(humidity, temperature, wind):

  results.append(np.fmin (humidity[h]['high'], np.fmin( temperature[t]['normal'], wind[w]['breeze']) ) )

但是如果我在控制台中寫了(Spyder,python 2.7):

 result = np.fmin (humidity[0]['high'], np.fmin( temperature[0]['normal'], wind[0]['breeze']) )

我得到20,這是真的。 但是,為什么我不能遍歷整個詞典呢? 怎么了?

非常感謝您的回答/想法!

您需要引用您的h,t,w變量而不是原始列表

results.append(np.fmin (h['high'], np.fmin( t['normal'], w['breeze']) ) )

因為h,t,w是從zip中解壓縮的字典,而不是int所以您不能使用它們來索引列表

可見, humidity[h]['high']看起來像

humidity[{'high': 90, 'middle': 50, 'low': 10}]['high']

在語法上沒有意義

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM