Issue
I have an array of numbers such as (only as an example) [40, 23, 15, 8]. I want to substract the last elemet to the previous one, and then. It'd look like [40-23, 23-15, 15-8, 8]. I want to apply this for an arbitrary array that goes from biggest to smallest.
I know I should iterate over my array but I'm currently blank on how to do it. Thanks in advance.
Solution
You don't need numpy
for this, it's easily accomplished in raw Python by iterating over the indices:
>>> a = [40, 23, 15, 8]
>>> [a[i] - sum(a[i + 1:]) for i in range(len(a))]
[-6, 0, 7, 8]
# The above answers the original question,
# in which the OP said: It'd look like [40-23-15-8, 23-15-8, 15-8, 8].
# - where all subsequent elements are subtracted from the first.
# As the question has now been edited, the following
# code answers the current version:
>>> [a[i] - (a[i + 1] if i < len(a) - 1 else 0) for i in range(len(a))]
[17, 8, 7, 8]
Answered By - teraspora
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.