代码点读机 / Python / -

- Python · 运算符

`-` 对数字做减法。对于集合,还可以做差集运算。就像从一堆东西里拿走一部分,剩下多少。

怎么用

数字1 - 数字2
集合1 - 集合2   # 差集

小例子

print(10 - 3)
print({1, 2, 3} - {2, 3, 4})   # 差集

运行结果

7
{1}

对比:字符串和列表不支持减法

print("hello" - "o")   # TypeError: unsupported operand type(s) for -: 'str' and 'str'

常见使用场景

1. 数学计算。
2. 集合差集:
所有用户 = {"小明", "小红", "小刚"}
已禁言用户 = {"小红"}
正常用户 = 所有用户 - 已禁言用户

提醒:- 数字可以是整数或浮点数。 - 集合差集表示在第一个集合但不在第二个集合中的元素。

官方文档:https://docs.python.org/zh-cn/3/tutorial/introduction.html#tut-numbers

在代码里遇到不认识的词?打开代码点读机,点一下就懂 → ← Python全部词条