为什么Python程序员仍然使用旧式除法?
我从 2001 年开始使用 Python。我喜欢这种语言的简单性,但一个让我恼火的功能是 /
运算符,它会在一些微妙的地方困扰我,比如
def mean(seq):
"""
Return the arithmetic mean of a list
(unless it just happens to contain all ints)
"""
return sum(seq) / len(seq)
幸运的是,PEP 238 已经写好了,当我发现新的 from __future__ import div
语句,我开始虔诚地将它添加到我编写的每个 .py 文件中。
但现在已经过去近 9 年了,我仍然经常看到 Python 代码示例,使用 /
用于整数除法。 //
不是一个广为人知的功能吗?或者实际上有理由选择旧的方式吗?
I started using Python in 2001. I loved the simplicity of the language, but one feature that annoyed the heck out of me was the /
operator, which would bite me in subtle places like
def mean(seq):
"""
Return the arithmetic mean of a list
(unless it just happens to contain all ints)
"""
return sum(seq) / len(seq)
Fortunately, PEP 238 had already been written, and as soon as I found about the new from __future__ import division
statement, I started religiously adding it to every .py file I wrote.
But here it is nearly 9 years later and I still frequently see Python code samples that use /
for integer division. Is //
not a widely-known feature? Or is there actually a reason to prefer the old way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对我来说,使用 int 进行除法总是有意义的,而 int 会产生一种通常不会进行即时类型转换的语言。
To me it's always made sense that dividing using ints gives and int result in a language that doesn't normally do on the fly type conversions.
如果您愿意,您可以更改整个解释器的
/
行为,因此无需在每个模块中从 future 导入You can change the behaviour of
/
for the whole interpreter if you prefer, so it's not necessary to import from future in every module我认为用于截断的
//
是众所周知的,但人们不愿意在他们编写的每个模块中“从未来导入”。经典方法(使用
float(sum(seq))
等获得浮点结果,使用int(...)
截断其他浮点除法)是你在 C++ 中使用的那个(在 C、Java、Fortran 等中的语法略有不同),以及在包含的 2.7 之前的每个 Python 版本中“本地”使用,所以如果很多人都使用它,也就不足为奇了非常习惯并且适应所说的“经典方法”。当 Python 3 变得比 Python 2 更广泛和广泛使用时,我预计情况会发生变化。
I think
//
for truncation is reasonably well known, but people are reluctant to "import from the future" in every module they write.The classic approach (using
float(sum(seq))
and so on to get a float result,int(...)
to truncate an otherwise-float division) is the one you'd use in C++ (and with slightly different syntax in C, Java, Fortran, ...), as well as "natively" in every Python release through 2.7 included, so it's hardly surprising if a lot of people are very used to, and comfortable with, said "classic approach".When Python 3 becomes more widespread and widely used than Python 2, I expect things to change.