将字典转换为数学表达式

Converting a dictionary to a mathematical expression

{'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}}}

需要对字典中的数字进行计算。

    Eg: {'YOU': {'HE': {'EST': 8, 'OLM': 6}, 'SLO': {'WLR': 8}},
 'WORK': {'KOE': {'RIW': 8, 'PNG': 4}, 'ROE': {'ERC': 8, 'WQD': 6}}} for this example the output would be

以下是我试过的代码:

a = [tuple([k]+list(v.keys())+list(j.values())) for k,v in data.items() for i,j in v.items()]

它给出:

[('YOU', 'HE', 'SLO', 8, 6),
 ('YOU', 'HE', 'SLO', 8),
 ('ARE', 'KLP', 'POL', 6),
 ('ARE', 'KLP', 'POL', 4),
 ('DOING', 'TIS', 8),
 ('GREAT', 'POL', 6),
 ('WORK', 'KOE', 'ROE', 8, 4),
 ('WORK', 'KOE', 'ROE', 8, 6),
 ('KEEP', 'PAR', 'PIL', 8, 6),
 ('KEEP', 'PAR', 'PIL', 4, 8),
 ('ROCKING', 'OUL', 6, 8)]

注意

无论如何不要使用eval,它是不安全的(“eval is evil”)。

有关 eval 危害的更多详细信息(太多了,我只有 cherry-picked 一个)阅读 here

一些解决方案的灵感

正如其他人和比我更聪明的人指出的那样,我没有找到关于您提供的示例中操作数分配的任何合理解释。

不过,这是一个小小的尝试 - 希望它能帮助您应对挑战。

所以给你:

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}')

规则不是 well-defined,但我还是会试一试。我假设您只想将此计算应用于嵌套字典中的键 YOUWORK。我认为列表理解会变得非常复杂,并且使用循环更易读。

对于每个键 YOUWORK,我总结了这两组最里面的值 8+6, 8 for YOU8+4, 8+6 for WORK,将这些值乘以 14*8 得到 YOU12*14 得到 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