在Python中用单行定义一个函数

时间:2016-06-25 10:01:59

标签: python

def two_of_three(a, b, c):
"""Return x*x + y*y, where x and y are the two largest members of the
positive numbers a, b, and c.

>>> two_of_three(1, 2, 3)
13
>>> two_of_three(5, 3, 1)
34
>>> two_of_three(10, 2, 8)
164
>>> two_of_three(5, 5, 5)
50
"""
return _____ 

只使用一行代表函数体,我该如何制作呢?

2 个答案:

答案 0 :(得分:1)

可能没有正当理由可以在一行上完成,但可以使用lambda完成:

>>> two_of_three = lambda a, b, c: sum(i*i for i in sorted((a,b,c))[-2:])

>>> two_of_three(1, 2, 3)
13
>>> two_of_three(5, 3, 1)
34
>>> two_of_three(10, 2, 8)
164
>>> two_of_three(5, 5, 5)
50

或在一行上使用def

def two_of_three(a,b,c): return sum(i*i for i in sorted((a,b,c))[-2:])

但为什么不以可读的方式做呢?

def two_of_three(a,b,c):
    """Return x*x + y*y, where x and y are the two largest members of the positive numbers a, b, and c"""
    return sum(i*i for i in sorted((a,b,c))[-2:])

答案 1 :(得分:0)

这不是你会做的事情,但这有效:

def two_of_three(a, b, c):
    return sum(x**2 for x in sorted([a, b, c])[1:])