我有一个项目列表,我想返回一个最严重的项目,即输入可能是" Rainy | Icy | Windy"
并且可能的输入列表(按严重程度排列):晴天,阴天,刮风,下雨,结冰。
通过上面的输入,我想输出Icy,因为它是最严重的。
我尝试过类似的事情:
dictionary1 = {'sunny': 0, 'cloudy': 1, 'windy': 1, 'rainy': 2, 'icy': 3}
with open(Conditions_csv, 'wb') as fw:
writer = csv.writer(fw, delimiter=',')
header = ['Date','latitude','longitude','Condition']
writer.writerow(header)
for row in cur.fetchall():
conditions = row[3].split("|")
for item in sorted(dictionary1.keys(),reverse= True):
name = dictionary1[item]
if name in conditions:
print row
print name
writer.writerow(row + name)
db.close()
上面的输出将是:
(18/12/2017,45,-85, Rainy|Icy|Windy)
Icy
(18/12/2017,45,-85, Rainy|Icy|Windy)
Rainy
(18/12/2017,45,-85, Rainy|Icy|Windy)
Windy
(18/12/2017,47,-88, Rainy|Windy)
Rainy
(18/12/2017,47,-88, Rainy|Windy)
Windy
(18/12/2017,40,-84, Icy|Windy)
Icy
(18/12/2017,40,-84, Icy|Windy)
Windy
所有我想要重申的是:
(18/12/2017,45,-85, Rainy|Icy|Windy)
Icy
(18/12/2017,47,-88, Rainy|Windy)
Rainy
(18/12/2017,40,-84, Icy|Windy)
Icy
答案 0 :(得分:5)
内置的max
函数允许您传递一个可选的key
参数,该参数执行我认为您要求的参数:
>>> severities = {'sunny': 0, 'cloudy': 1, 'windy': 1, 'rainy': 2, 'icy': 3}
>>> max(['sunny', 'cloudy', 'windy', 'rainy', 'icy'], key=lambda s: severities[s])
'icy'
答案 1 :(得分:0)
以下是我用于答案的原因:FYI:
with open(Conditions_csv, 'wb') as fw:
writer = csv.writer(fw, delimiter=',')
header = ['Date','latitude','longitude','Condition']
writer.writerow(header)
for row in cur.fetchall():
conditions = row[3].split("|")
Final = max(conditions, key=lambda s: dictionary[s])
myList= row[0],float(row[1]),float(row[2]),Final
writer.writerow(myList)
db.close()