本文介绍了Python sum() 导入numpy后结果不一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I came across this problem by Jake VanderPlas and I am not sure if my understanding of why the result differs after importing the numpy module is entirely correct.

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

似乎在第一种情况下,sum 函数计算可迭代对象的总和,然后从总和中减去第二个 args 值.

It seems like in the first scenario the sum function calculates the sum over the iterable and then subtracts the second args value from the sum.

在第二种情况下,在导入 numpy 之后,函数的行为似乎发生了变化,因为第二个 arg 用于指定应沿其执行求和的轴.

In the second scenario, after importing numpy, the behavior of the function seems to have modified as the second arg is used to specify the axis along which the sum should be performed.

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

Exercise number (24)Source - http://www.labri.fr/perso/nrougier/teaching/numpy.100/index.html

推荐答案

仅将我的 5 个迂腐硬币添加到 @Warren Weckesser回答.真的from numpy import * 是不正确的.对于数字来说,加/减 之后.但对于列表来说确实如此(愚蠢的例子只是为了说明这个想法):

I your case print(sum(range(5),-1) for built-in sum summation starts with -1. So technically, your phrase isn't correct. For numbers it's really does not matter to start with or add/subtract later. But for lists it does (silly example only to show the idea):

 In[1]: sum([[1], [2], [3]], [4])
Out[1]: [4, 1, 2, 3]               # not [1, 2, 3, 4]

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

Hope this will clarify your thoughts :)

这篇关于Python sum() 导入numpy后结果不一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!