python 比较三个值的方法(条件运算、三目运算、list运算)

假设有这么一道题,拿reserve去跟first和second两个值进行比较,逻辑如下:
second <——0 < reserve <= second
count <—— second < reserve <= first
0 <——otherwise
实现方法如下:

  1. 条件运算
def compare(reserve, first, second):
    """
    second    0 < reserve <= second
    count    second < reserve <= first
    0    otherwise
    """
    if 0 < reserve <= second:
        print(second)
    elif second < reserve <= first:
        print(reserve)
    else:
        print(0)


if __name__ == '__main__':
    compare(3, 2, 1)
  1. 三目运算
def compare(reserve, first, second):
    """
    second    0 < reserve <= second
    count    second < reserve <= first
    0    otherwise
    """
    # 条件为真的赋值 if 条件 else 条件为假的赋值
    result = second if 0 < reserve <= second else (reserve if second < reserve <= first else 0)
    print(result)


if __name__ == '__main__':
    compare(3, 2, 1)
  1. list运算
def compare(reserve, first, second):
    """ list取代三目运算 """
    """
    second    0 < reserve <= second
    count    second < reserve <= first
    0    otherwise
    """
    # list[条件为假的赋值,条件为真的赋值][条件]
    san_list = [[0, reserve][second < reserve <= first], second][0 < reserve <= second]
    print(san_list)


if __name__ == '__main__':
    compare(3, 2, 1)
posted @ 2023-04-22 21:04  七夜魔手  阅读(4)  评论(0编辑  收藏  举报  来源