Discuss / Python / imaima

imaima

Topic source

from functools import reduce

def str2num(s):

    return int and float (s)

def calc(exp):

    ss = exp.split('+')

    ns = map(str2num, ss)

    return reduce(lambda acc, x: acc + x, ns)

def main():

    r = calc('100 + 200 + 345')

    print('100 + 200 + 345 =', r)

    r = calc('99 + 88 + 7.6')

    print('99 + 88 + 7.6 =', r)

main()

Daicy

#2 Created at ... [Delete] [Delete and Lock User]

经过测试以下代码

经过测试你的

Daicy

#3 Created at ... [Delete] [Delete and Lock User]

经过测试以下代码

def str2num(s):
    return int and float (s)

等于return float(s)

但是这种写法以前没有见过, 解释器居然也没有报错, 我查了python官网, 对and的解释也只是布尔操作符, 不知道有没有大佬可以解释一下两个函数中加and的具体意思?

In fact, 'and' does act as a logical operator. When you write things like 'int and float(x)', ‘int' acts as a class object and operates on the actual float. This is the same as if you were to take a ‘float' class and compute it with an ‘int' class, and the resulting value would still Orient to the variable space pointed to by the ‘float' class. If you change the above notation to 'float and int(x)', you will see that the function still gives an error, because the actual function that operates on the variable is an ‘int' and not a ‘float'.


  • 1

Reply