Python - 嵌套函数,圆括号顺序

时间:2016-01-25 15:06:58

标签: python function

我遇到了一个问题,我需要编写一个函数,如果x小于lo,则输出为lox大于{{} {1}}输出为hi。否则输出将为hi。该问题的解决方案是:

x

有人可以在返回声明中解释括号的顺序吗?我试着这样写:

def hilo(lo, x, hi):

    return min(max(x, lo), hi)

但显然,这不起作用。

2 个答案:

答案 0 :(得分:3)

min(max(x,lo), hi)表示

  1. maxx作为参数调用lo
  2. 使用该呼叫的返回值min作为参数调用hi
  3. 假设值lohi以及函数minmax的语义隐含在它们的名称中,这个逻辑首先计算出{xlo之间哪个更大。 1}}和hi,然后它与lo之间的距离较小。因此保证结果不小于hi且不大于x;如果x在该范围内,则返回x本身,否则返回范围最接近min(max(x,lo,hi)的结尾。

    然而,max表示:

    1. xlohi作为参数致电min
    2. 使用该调用的返回值作为唯一参数调用min
    3. 考虑到与语义匹配的名称相同的假设,这没有任何意义,因为hi只有一个参数,即使它不是错误,也只会返回那个参数不变。以上内容总是会返回xlo之间较大者,而<Jobs> <Job Category="Administration" Title="Senior Human Resource Coordinator"> <Description> <![CDATA[ Long description of the job goes here. ]]> </Description> <ShortDescription> <![CDATA[ Short description of the job goes here. ]]> </ShortDescription> <JobLocations> <Location Salary="$50000">Toronto</Location> <Location Salary="£40000">London</Location> </JobLocations> <Benefits>Drug, Dental, Optical and Extended Healthcare Benefits</Benefits> <Jobtype>Full-Time</Jobtype> </Job> <Job Category="Administration" Title="Junior Human Resource Coordinator"> <Description> <![CDATA[ Long description of the job goes here. ]]> </Description> <ShortDescription> <![CDATA[ Short description of the job goes here. ]]> </ShortDescription> <JobLocations> <Location Salary="$50000">Toronto</Location> <Location Salary="£40000">London</Location> </JobLocations> <Benefits>Drug, Dental, Optical and Extended Healthcare Benefits</Benefits> <Jobtype>Full-Time</Jobtype> </Job> </Jobs> 根本不会进入。{/ p>

答案 1 :(得分:1)

首先执行最里面的括号max(x, lo)中的函数。这会返回xlo之间的较大值。然后使用剩余的2个参数minxlo执行外部函数hi

使用max时,max(x, lo, hi)函数无法使用3个参数。 min也没有1个参数,max将返回。