我见过许多例子,其中需要从一个数字到另一个字的映射,或者相反的方向。
在我的情况下,我想从一系列值到单词
进行映射我有一本字典intelligence = {"John" : 100 , "Mike" : 80, "Peter" : 150}
我使用这个功能:
a = list()
for name,iq in intelligence.items():
if iq<=100:
smartness = "low iq"
a.append((name,iq),smartness ))
elif c>=100 and c<=95:
smartness = "mid"
a.append((name,iq),smartness ))
else:
smartness = "high"
a.append((name,iq),smartness ))
print a
正如您所看到的那样,代码有点冗余,更多的pythonic方式来实现这个结果?可能是一种完全不同的方法更好吗?
编辑后
a = list()
for name,iq in intelligence.items():
if iq<=100:
smartness = "low iq"
elif c>=100 and c<=95:
smartness = "mid"
else:
smartness = "high"
a.append((name,iq),smartness ))
print a
答案 0 :(得分:2)
def iq_to_distance(iq):
if iq<=95: return "low"
if iq<=100: return "mid"
return "high"
for name,iq in intelligence.items():
print {'name': name, 'iq': iq, 'distance': iq_to_distance(iq)}
输出:
{'iq': 80, 'distance': 'low', 'name': 'Mike'}
{'iq': 100, 'distance': 'mid', 'name': 'John'}
{'iq': 150, 'distance': 'high', 'name': 'Peter'}
请注意,我已经更改了一些数字,因为elif c>=100 and c<=95:
始终为False。
或一个班轮:
[{'name': name,
'iq': iq,
'distance': iq<=95 and "low" or iq<=100 and "mid" or "high"}
for name,iq in intelligence.items()]
输出:
[{'iq': 80, 'distance': 'low', 'name': 'Mike'},
{'iq': 100, 'distance': 'mid', 'name': 'John'},
{'iq': 150, 'distance': 'high', 'name': 'Peter'}]