简体   繁体   中英

Subtract dynamic value from every value in list

Apologies if my explanation below is poor, but I am fairly new to python scripting.

I'm trying to find a way to product a list of number that subtracting a set_value from an item in a list, then take the new_value and subtract it from the next item in the list, and so on.

For example:

subtraction_list = []
set_value = 100
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
set_value - list[0] = 99
new_set_value = 99
new_set_value - list[1] = 98
...
subtraction_list = [99, 97, 94, 90, 85, 79, 72, 64, 55, 45]

Regardless, any help would be greatly appreciated!

You can do this in a functional way by leveraging itertools.accumulate to make an iterator the yields the cumulative sum of your list.

It works like this:

from itertools import accumulate

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
m = accumulate([0] + l)  # in 3.8 we can use accumulate(l, initial = 0)

list(m)
# [0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55]

You can zip this with your value and use it as part of the subtraction allowing you to avoid explicitly managing the state of the variable:

from itertools import accumulate

set_value = 100

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
m = accumulate([0]+l)

subtraction_list = [set_value - diff - n for diff, n in zip(m, l)]
# [99, 97, 94, 90, 85, 79, 72, 64, 55, 45]

For something completely different – if you are using python 3.8, you can use the walrus := operator here:

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
set_value  = 100
subtraction_list = [set_value := set_value - n for n in l]

[One note: don't use list as a variable name. list is a built-in type in python that you can overwrite, which leads to hard-to-find bugs.]

First, you shouldn't use the variable name list , because it's the name of a built-in function, so you can try this with a simple loop:

set_value = 100
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
final_list=[]
for i in lst:
    final_list.append(set_value-i)
    set_value=set_value-i
final_list
>>>[99, 97, 94, 90, 85, 79, 72, 64, 55, 45]

Simlply loop through the list

subtraction_list = []
set_value = 100
list_of = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

for i in range(len(list_of)):
    set_value = set_value - list_of[i]
    subtraction_list.append(set_value)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM