python 比较三个值的方法(条件运算、三目运算、list运算)
假设有这么一道题,拿reserve去跟first和second两个值进行比较,逻辑如下:
second <——0 < reserve <= second
count <—— second < reserve <= first
0 <——otherwise
实现方法如下:
- 条件运算
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)
- 三目运算
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)
- 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)
本文来自博客园,作者:七夜魔手,转载请注明原文链接:https://www.cnblogs.com/ranbox/p/18461100