Skip to content

Latest commit

 

History

History
33 lines (25 loc) · 657 Bytes

17.md

File metadata and controls

33 lines (25 loc) · 657 Bytes
@author jackzhenguo
@desc 
@date 2019/2/15

17 计算表达式

将字符串str 当成有效的表达式来求值并返回计算结果取出字符串中内容

In [1]: s = "1 + 3 +5"

In [2]: eval(s)
Out[2]: 9

s = ["{'小汽车':10, '面包车':8}", "{'面包车':5}"]
from collections import defaultdict
d = defaultdict(int)

for item in s:
    my_dict = eval(item)
    print(type(my_dict))
    for key in my_dict:
        d[key] += my_dict[key]
print(d)

<class 'dict'>
<class 'dict'>
defaultdict(<class 'int'>, {'小汽车': 10, '面包车': 13})
[上一个例子](16.md) [下一个例子](18.md)