找出三个数字的中间 [英] Finding the middle of three numbers

查看:262
本文介绍了找出三个数字的中间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找其他或更简洁的方法来返回三个唯一值的中间值.我现在拥有的是一个功能:

I'm looking for alternative or more concise ways to return the middle of three unique values. What I have right now is a function:

def middle(x, y, z):
    if x > y and x < z:
        return x
    if y > x and y < z:
        return y
    return z

还有什么更好的吗?

推荐答案

def middle(x, y, z):
    return sorted([x, y, z])[1]

这应该返回中间数字.但是,如果您实际上是指最大数量

This should return the middle number. But if you actually meant maximum number

def maximum(x, y, z):
    return max([x, y, z])

编辑:如abarnert在评论部分所建议的那样,请使用 x< x代替 y> x和x< z .&z ,更具可读性和Python风格.

As suggested by abarnert in the comments section, instead of y>x and x<z use x < y < z, which is more readable and pythonic.

这篇关于找出三个数字的中间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆