python基础编程_33_eval函数的使用

eval
  功能:将字符串str当成有效的表达式来求值并返回计算结果。
  语法: eval(source[, globals[, locals]]) -> value
  参数:
    source:一个Python表达式或函数compile()返回的代码对象
    globals:可选。必须是dictionary
    locals:可选。任意map对象
  实例展示:
num=[5,5,5,5,5]
result=5
for i in ['+','-','*','/']:
    for j in ['+','-','*','/']:
        for k in ['+','-','*','/']:
            for z in ['+','-','*','/']:
                if eval(str(num[0])+i+str(num[1])+j+str(num[2])+k+str(num[3])+z+str(num[4]))==result:
                    print(str(num[0])+i+str(num[1])+j+str(num[2])+k+str(num[3])+z+str(num[4])+'=5')
5+5+5-5-5=5
5+5-5+5-5=5
5+5-5-5+5=5
5+5-5*5/5=5
5+5-5/5*5=5
5+5*5-5*5=5
5+5*5/5-5=5
5+5/5-5/5=5
5+5/5*5-5=5
5-5+5+5-5=5
5-5+5-5+5=5
5-5+5*5/5=5
5-5+5/5*5=5
5-5-5+5+5=5
5-5*5+5*5=5
5-5*5/5+5=5
5-5/5+5/5=5
5-5/5*5+5=5
5*5+5-5*5=5
5*5-5*5+5=5
5*5*5/5/5=5
5*5/5+5-5=5
5*5/5-5+5=5
5*5/5*5/5=5
5*5/5/5*5=5
5/5+5-5/5=5
5/5-5/5+5=5
5/5*5+5-5=5
5/5*5-5+5=5
5/5*5*5/5=5
5/5*5/5*5=5
5/5/5*5*5=5
                    
 >>>a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
 5 >>>type(a)
 6 
 7 >>> b = eval(a)
 8 >>> print b
 9 [[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
10 >>> type(b)
11 
12 
13 字符串转换成字典
14 >>> a = "{1: 'a', 2: 'b'}"
15 >>> type(a)
16 
17 >>> b = eval(a)
18 >>> print b
19 {1: 'a', 2: 'b'}
20 >>> type(b)
21 


你可能感兴趣的:(python)