Python sum()在导入numpy后有不同的结果

2024-03-29 01:26:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了Jake VanderPlas的这个问题,我不确定我对导入numpy模块后结果不同的理解是否完全正确。在

>>print(sum(range(5),-1)
>> 9
>> from numpy import *
>> print(sum(range(5),-1))
>> 10

似乎在第一个场景中,sum函数计算iterable上的和,然后从sum中减去第二个args值。在

在第二个场景中,在导入numpy之后,函数的行为似乎已经修改,因为第二个参数用于指定应该沿着哪个轴执行求和。在

练习编号(24) 源-http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html


Tags: 模块函数fromimportnumpy参数场景args
2条回答

“函数的行为似乎已被修改,因为第二个参数用于指定应沿其执行总和的轴。”

你基本上回答了你自己的问题!在

说函数的行为已被修改在技术上是不正确的。from numpy import *会导致使用numpy ^{} function来“隐藏”builtin ^{} function,因此当您使用名称sum时,Python会找到numpy版本而不是内置版本(有关更多详细信息,请参阅@godaygo的答案)。这些函数的参数不同。通常使用from somelib import *是个坏主意,正是因为这个原因。相反,请使用import numpy as np,然后在需要numpy函数时使用np.sum,在需要Python内置函数时使用普通sum。在

只是为了给@Warren Weckesser答案加上我的5个书呆子硬币。实际上,from numpy import *不会覆盖builtinssum函数,它只覆盖__builtins__.sum,因为from ... import *语句将导入模块中定义的所有名称(以下划线开头的名称除外)绑定到当前的global命名空间。并且根据Python的名称解析规则(非官方的LEGB规则),在__builtins__名称空间之前查找global名称空间。因此,如果Python找到所需的名称,在您的例子中是sum,它将返回绑定对象,而不再进一步查看。在

编辑: 向您展示发生了什么:

 In[1]: print(sum, ' from ', sum.__module__)    # here you see the standard `sum` function
Out[1]: <built-in function sum>  from  builtins

 In[2]: from numpy import *                     # from here it is shadowed
        print(sum, ' from ', sum.__module__)
Out[2]: <function sum at 0x00000229B30E2730>  from  numpy.core.fromnumeric

 In[3]: del sum                                 # here you restore things back
        print(sum, ' from ', sum.__module__)
Out[3]: <built-in function sum>  from  builtins

第一个注意事项del不删除对象,它是垃圾收集器的一项任务,它只“取消引用”名称绑定并从当前命名空间中删除名称。在

第二个注意事项:内置sum函数的签名是sum(iterable[, start])

Sums start and the items of an iterable from left to right and returns the total. start defaults to 0. The iterable‘s items are normally numbers, and the start value is not allowed to be a string.

我您的例子print(sum(range(5),-1)内置的sum求和从-1开始。所以从技术上讲,你的短语在iterable上求和然后从sum中减去第二个args值是不正确的。以后再加上或不重要。但对于列表,它确实是这样的(这个愚蠢的例子只是为了展示这个想法):

^{pr2}$

希望这能澄清你的想法:)

相关问题 更多 >