python中数值比较大小的8种经典比较方法,不允许你还不知道
在 Python 中比较数值大小是基础但重要的操作。以下是 8 种经典比较方法及其应用场景,从基础到进阶的完整指南:
1. 基础比较运算符
Python 提供 6 种基础比较运算符:
a, b = 5, 3
print(a > b) # True 大于
print(a < b) # False 小于
print(a >= b) # True 大于等于
print(a <= b) # False 小于等于
print(a == b) # False 等于
print(a != b) # True 不等于
2. 多条件链式比较
Python 支持数学式的链式比较:
x = 10
print(5 < x < 15) # True (等效于 5 < x and x < 15)
print(0 <= x <= 100) # True
# 实际应用:判断成绩等级
score = 85
print(80 <= score < 90) # True (B等级)
3. 使用内置函数
max() / min() 函数
nums = [12, 5, 8, 20]
print(max(nums)) # 20
print(min(nums)) # 5
# 比较多个变量
a, b, c = 7, 10, 3
print(max(a, b, c)) # 10
sorted() 排序比较
values = [15, 2, 30]
sorted_values = sorted(values) # [2, 15, 30]
print(f"最小值:{sorted_values[0]},最大值:{sorted_values[-1]}")
4. 处理浮点数精度问题
浮点数比较需考虑精度误差:
# 错误方式
print(0.1 + 0.2 == 0.3) # False
# 正确方式
tolerance = 1e-9 # 设定误差容忍度
print(abs((0.1 + 0.2) - 0.3) < tolerance) # True
5. 自定义对象比较
通过 __lt__, __eq__ 等魔术方法实现:
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def __lt__(self, other): # 实现 < 运算符
return self.price < other.price
# 比较测试
p1 = Product("鼠标", 50)
p2 = Product("键盘", 80)
print(p1 < p2) # True (比较价格)
6. 实用案例集合
案例1:找三个数中最大值
a, b, c = 12, 7, 9
max_value = a if a > b and a > c else (b if b > c else c)
print(max_value) # 12
案例2:判断闰年
year = 2024
is_leap = (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)
print(is_leap) # True
案例3:价格折扣判断
price = 120
discount = 0.2 if price > 100 else 0.1
print(f"最终价格:{price * (1 - discount):.2f}")
7. 进阶技巧
使用海象运算符 (Python 3.8+)
if (n := int(input("输入数字:"))) > 10:
print(f"{n}大于10")
利用布尔值当索引
a, b = 10, 20
result = (b, a)[a > b] # 如果a>b选a,否则选b
print(result) # 20
8. 性能对比
方法 | 时间复杂度 | 适用场景 |
直接比较 | O(1) | 简单数值比较 |
max()/min() | O(n) | 找列表极值 |
sorted() | O(n log n) | 需要排序时 |
numpy.argmax() | O(n) | 大数据量(需安装numpy) |
9. 常见问题解答
Q1:如何比较字符串数字?
num_str = "123"
print(int(num_str) > 100) # 先转为数值
Q2:==和is的区别?
a = 256
b = 256
print(a == b) # True (值相等)
print(a is b) # True (小整数池优化)
x = 257
y = 257
print(x == y) # True
print(x is y) # False (非同一对象)
Q3:如何比较日期?
from datetime import date
d1 = date(2023, 1, 1)
d2 = date.today()
print(d1 < d2) # True
10. 综合练习
- 编写函数返回两个数字中更接近10的值:
def closer_to_ten(a, b):
return a if abs(a - 10) < abs(b - 10) else b
- 实现三数排序:
a, b, c = 15, 7, 22
sorted_nums = sorted((a, b, c))
print(f"排序结果:{sorted_nums}")
- 处理用户输入比较:
try:
x = float(input("输入第一个数字:"))
y = float(input("输入第二个数字:"))
print(f"较大值:{max(x, y)}")
except ValueError:
print("请输入有效数字!")
掌握数值比较后,可以进一步学习:
- NumPy 数组比较
- Pandas 数据筛选
- 自定义排序规则(如 sorted(key=lambda...))