2 回答
![?](http://img1.sycdn.imooc.com/545847aa0001063202200220-100-100.jpg)
TA贡献1828条经验 获得超13个赞
规则没有明确定义,但无论如何我都会尝试一下。我假设您只想将此计算应用于键YOU和WORK嵌套字典中。我认为列表理解会变得非常复杂,并且使用循环更具可读性。
对于每个键YOU和WORK,我总结了这两组最里面的值8+6, 8forYOU和8+4, 8+6for WORK,将这些值相乘在一起14*8forYOU和12*14for WORK,然后将乘积加在一起得到结果 =280
dict_nested = {'YOU': {'HE': {'EST': 8, 'OLM': 6}, 'SLO': {'WLR': 8}},
'ARE': {'KLP': {'EST': 6}, 'POL': {'WLR': 4}},
'DOING': {'TIS': {'OIL': 8}},
'GREAT': {'POL': {'EOL': 6}},
'WORK': {'KOE': {'RIW': 8, 'PNG': 4}, 'ROE': {'ERC': 8, 'WQD': 6}},
'KEEP': {'PAR': {'KOM': 8, 'RTW': 6}, 'PIL': {'XCE': 4, 'ACE': 8}},
'ROCKING': {'OUL': {'AZS': 6, 'RVX': 8}}}
keys = ['YOU','WORK']
result = 0
for key in keys:
inner_keys = dict_nested[key].keys()
# multiply the values together for the first values of the inner key
inner_product = 1
for inner_key in inner_keys:
inner_product *= sum(list(dict_nested[key][inner_key].values()))
# print(inner_product)
result += inner_product
输出:
>>> result
280
![?](http://img1.sycdn.imooc.com/545845b40001de9902200220-100-100.jpg)
TA贡献1810条经验 获得超4个赞
笔记
无论如何不要使用eval,它是不安全的(“eval 是邪恶的”)。
有关危害性的更多详细信息eval(有太多,我只是挑选了一个)请阅读此处。
解决方案的一些灵感
正如我之前的其他人和更聪明的人所指出的那样,我在您提供的示例中没有找到有关操作数分配的任何合理解释。
然而,这只是一个小小的尝试——希望它能帮助你应对挑战。
所以你开始吧:
import json
d = {'YOU': {'HE': {'EST': 8, 'OLM': 6}, 'SLO': {'WLR': 8}}, 'WORK': {'KOE': {'RIW': 8, 'PNG': 4}, 'ROE': {'ERC': 8, 'WQD': 6}}}
# Convet dictionary to a string
r = json.dumps(d)
# Convert string to char list
chars = list(r)
# Legal chars needed for computing
legal_chars = ['{', '}', ','] + [str(d) for d in range(10)]
# Filtering in only legal chars
filtered_chars = [x for x in chars if x in legal_chars]
# Replacing the {} with () and , with +
expression = ''.join(filtered_chars).replace('{', '(').replace('}', ')').replace(',', '+')
# Evaluating expression
result = eval(expression)
# (((8+6)+(12))+((8+4)+(8+6)))=52
print(f'{expression}={result}')
添加回答
举报