英文:
Numpy : cumulative difference in a list
问题
我被卡在一个迭代问题上。
我有一个数字列表,像这样:list = [100, 70, 25, 10, 5]。
我想遍历这个列表并生成一个新数组,使得每个“result”都成为下一个数字被减去的新数字:
100-70 = 30
30(结果)- 25 = 5
5(结果)- 10 = -5
-5(结果)- 5 = -10
(我想你明白了)。
new_array = [30, 5, -5, -10]
我无法用Numpy得出解决方案。
任何帮助都会很感激!
谢谢!
英文:
I'm stuck on a iteration problem.
I have a list of numbers, like: list = [100, 70, 25, 10, 5].
I would like to iterate over the list and generate a new array, such that each "result" becomes the new number from which the next is subtracted:
100-70 = 30
30 (result) - 25 = 5
5 (result) - 10 = -5
-5 (result) - 5 = -10
(I think you get the idea)
new_array = [30, 5, -5, -10]
I am not able to arrive at the solution with Numpy.
Any help is appreciated!
Thank you!
答案1
得分: 5
你可以使用 numpy.ufunc.accumulate 来执行减法操作。
numbers = [100, 70, 25, 10, 5]
result = np.subtract.accumulate(numbers)[1:]
print(result)
输出:
[ 30 5 -5 -10]
英文:
You can use the subtract ufunc with numpy.ufunc.accumulate.
numbers = [100, 70, 25, 10, 5]
result = np.subtract.accumulate(numbers)[1:]
print(result)
Output:
[ 30 5 -5 -10]
答案2
得分: 1
以下是您提供的代码的中文翻译:
如果有人想要在没有使用numpy的情况下执行此操作:
from itertools import accumulate
import operator
data = [100, 70, 25, 10, 5]
result = list(accumulate(data, operator.sub))[1:]
英文:
In case anyone's looking to do this without numpy:
from itertools import accumulate
import operator
data = [100, 70, 25, 10, 5]
result = list(accumulate(data, operator.sub))[1:]
答案3
得分: 0
这应该可以工作 -
main = [100,70,25,10,5]
new_main = [] # 修改此行
current_difference = main[0]
for element in main[1:]:
new_main.append(current_difference - element)
current_difference -= element
new_main.append(current_difference - main[-1])
print(new_main)
英文:
This should work -
main = [100,70,25,10,5]
new_main = [] #modified this line
current_difference = main[0]
for element in main[1:]:
new_main.append(current_difference - element)
current_difference-=element
new_main.append(current_difference - main[-1])
print(new_main)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论