python2.7 中的函数 operator.idiv 似乎在 python 3.4 中不存在。这个功能是不是没有了或者现在在哪里可以找到?
import operator
operator.idiv
>>> AttributeError: module 'operator' has no attribute 'idiv'
最佳答案
在 Python 3 中,根据 PEP 238 ,默认的除法运算符 /
被修改为始终返回 float 结果,无论输入类型如何。因此,虽然在 Python 2 中 3/2
和 3.0/2
会返回不同的结果,但您现在在 Python 3 中会得到一致的 float 结果:
>>> 3 / 2
1.5
>>> 3.0 / 2
1.5
>>> 3 / 2.0
1.5
另一个除法运算符是 floor 除法 //
,它对结果进行除法(截断小数位)。请注意,此运算符仍然尊重输入类型,因此将它与两个 int 一起使用会得到一个 int,而使用 float 也会将结果变成 float:
>>> 3 // 2
1
>>> 3 // 2.0
1.0
>>> 3.0 // 2
1.0
所以答案是,是的,“经典”除法运算符在 Python 3 中消失了。只有一个“真正的”除法(导致 float )和一个底除法,可以使用 operator.itruediv
和 operator.ifloordiv
分别。
关于python - python3中的operator.idiv在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37600171/