简体   繁体   中英

How to subtract backwards in a list in Python 3?

I am trying to subtract a list backwards in Python. This is the code:

list_1 = [1,2,5,7,9,85]

The subtraction should go like this: index 1 - index 0, index 2 - index 1, and so on and so forth. This is the output:

1
3
2
2
76

How can i do something like this using Python 3?

Using map and operator and itertools.islice , this way you are avoiding intermediate lists creation or memory overhead and also avoids using python native for loop:

import operator
from itertools import islice
list_1 = [1,2,5,7,9,85]

result = list(map(operator.sub, islice(list_1, 1, None),list_1))

Here you have a live example

使用zip

[i - j for i, j in zip(list_1[1:], list_1)]

You can use a good old-fashioned for loop:

for i in range(1, len(list_1)):
    print list_1[i]-list_1[i-1]

Try this:

list_1 = [1,2,5,7,9,85]
for i in range(len(list_1)-1,1,-1):
    list_1[i] = list_1[i]-list_1[i-1]
print(list_1)

Note: iterate backwards to get expected answer.

One-liner using list comprehension.

Iterate from zero to the penultimate index and do the subtraction.

[ (list_1[i+1] - list_1[i]) for i in range(len(list_1)-1)]
    print [a[i+1]- a[i] for i in range(len(a)-1)]

这种单行返回一个列表,其元素是list_1中连续数字的差。

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