博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python Division //
阅读量:4030 次
发布时间:2019-05-24

本文共 1754 字,大约阅读时间需要 5 分钟。

In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e. quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/33>>> # to get a floating point number from integer division:>>> 10.0/33.3333333333333335>>> float(10)/33.3333333333333335

In Python 3:

>>> 10/33.3333333333333335>>> 10//33

For further reference, see .

// is unconditionally "truncating division", e.g:

>>> 4.0//1.52.0

As you see, even though both operands are floats, // still truncates -- so you always know securely what it's gonna do.

Single / may or may not truncate depending on Python release, future imports, and even flags on which Python's run, e.g....:

$ python2.6 -Qold -c 'print 2/3'0$ python2.6 -Qnew -c 'print 2/3'0.666666666667

As you see, single / may truncate, or it may return a float, based on completely non-local issues, up to and including the value of the -Q flag...;-).

So, if and when you know you want truncation, always use //, which guarantees it. If and when you know you don't want truncation, slap a float() around other operand and use /. Any other combination, and you're at the mercy of version, imports, and flags!-)

To complement these other answers, the // operator also offers significant (3x) performance benefits over /, presuming you want integer division.

$ python -m timeit '20.5 // 2'100000000 loops, best of 3: 0.0149 usec per loop$ python -m timeit '20.5 / 2'10000000 loops, best of 3: 0.0484 usec per loop$ python -m timeit '20 / 2'10000000 loops, best of 3: 0.043 usec per loop$ python -m timeit '20 // 2'100000000 loops, best of 3: 0.0144 usec per loop

转载地址:http://iihbi.baihongyu.com/

你可能感兴趣的文章
持续可用与CAP理论 – 一个系统开发者的观点
查看>>
nginx+tomcat+memcached (msm)实现 session同步复制
查看>>
c++指针常量与常量指针详解
查看>>
c++字符数组和字符指针区别以及str***函数
查看>>
c++类的操作符重载注意事项
查看>>
c++模板与泛型编程
查看>>
STL::deque以及由其实现的queue和stack
查看>>
CS4344驱动
查看>>
WAV文件解析
查看>>
DAC输出音乐2-解决pu pu 声
查看>>
WPF中PATH使用AI导出SVG的方法
查看>>
WPF UI&控件免费开源库
查看>>
QT打开项目提示no valid settings file could be found
查看>>
Win10+VS+ESP32环境搭建
查看>>
Ubuntu+win10远程桌面
查看>>
flutter-实现圆角带边框的view(android无效)
查看>>
flutter-实现一个下拉刷新上拉加载的列表
查看>>
android 代码实现圆角
查看>>
postman调试webservice接口
查看>>
flutter-解析json
查看>>