这里写自定义目录标题
一样的代码,两次调用的输出截然不同
100 numpy exercises 中有个有趣的题目
26.What is the output of the following script? (★☆☆)
print(sum(range(5),-1))
from numpy import *
print(sum(range(5),-1))
两行打印分别是9和10,是不是有些奇怪?
分析原因
首先来看第一行打印:
print(sum(range(5),-1))
这里调用的是python原生的sum接口。
第二行,因为导入了numpy包,再调用sum()就会被numpy中sum()覆盖,因此第三行中的sum(),调用的已不是python原生的sum()接口了,而是numpy.sum()。
可以使用help(sum)
确认调用的是哪个包里面的sum函数。
Help on built-in function sum in module __builtin__:
sum(...)
sum(sequence[, start]) -> value
Return the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, return start.
Help on function sum in module numpy.core.fromnumeric:
sum(a, axis=None, dtype=None, out=None, keepdims=<no value>, initial=<no value>)
Sum of array elements over a given axis.
Parameters
----------
a : array_like
Elements to sum.
axis : None or int or tuple of ints, optional
Axis or axes along which a sum is performed. The default,
axis=None, will sum all of the elements of the input array. If
axis is negative it counts from the last to the first axis.
.. versionadded:: 1.7.0
If axis is a tuple of ints, a sum is performed on all of the axes
specified in the tuple instead of a single axis or all the axes as
before.
dtype : dtype, optional
The type of the returned array and of the accumulator in which the
elements are summed. The dtype of `a` is used by default unless `a`
has an integer dtype of less precision than the default platform
:
下面的博客详细分析了具体原因。
https://stoneboy100200.github.io/2018/08/09/numpy-sum/
https://blog.csdn.net/linzch3/article/details/60141743