python – 字典的平方值
发布时间:2020-12-20 12:33:30 所属栏目:Python 来源:网络整理
导读:我正在使用 Python 2.7,仍在学习字典.我专注于为字典执行数值计算,需要一些帮助. 我有一本字典,我想对其中的值进行平方: dict1 = {'dog': {'shepherd': 5,'collie': 15,'poodle': 3,'terrier': 20},'cat': {'siamese': 3,'persian': 2,'dsh': 16,'dls': 16}
我正在使用
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,'parrot': 4} 我试过了: dict1_squared = dict**2. dict1_squared = pow(dict,2.) dict1_squared = {key: pow(value,2.) for key,value in dict1.items()} 我的尝试没有任何成功. 解决方法
你非常接近字典理解.问题是您的解决方案中的值本身就是字典,所以您也必须迭代它.
dict1_squared = {key: {k: pow(v,2) for k,v in value.items()} for key,value in dict1.items()} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |