我正在使用 Python 2.7,仍在学习字典。我专注于为字典执行数值计算,需要一些帮助。
我有一本字典,我想对其中的值求平方:
dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},
'cat': {'siamese': 3,'persian': 2,'dsh': 16,'dls': 16},
'bird': {'budgie': 20,'finch': 35,'cockatoo': 1,'parrot': 2}
我要:
dict1 = {'dog': {'shepherd': 25,'collie': 225,'poodle': 9,'terrier': 400},
'cat': {'siamese': 9,'persian': 4,'dsh': 256,'dls': 256},
'bird': {'budgie': 400,'finch': 1225,'cockatoo': 1,'parrot': 4}
我试过:
dict1_squared = dict**2.
dict1_squared = pow(dict,2.)
dict1_squared = {key: pow(value,2.) for key, value in dict1.items()}
我的尝试没有任何成功。
最佳答案
其中一个我可能更喜欢循环的情况:
for d in dict1.values():
for k in d:
d[k] **= 2
关于python - 字典的平方值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39067114/