How to subtract backwards in a list in Python 3?

时间:2018-06-20 05:05:25

标签: python python-3.x

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?

6 个答案:

答案 0 :(得分:4)

使用mapoperatoritertools.islice,这样可以避免中间列表的创建或内存开销,也可以避免使用python native for循环:

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))

您在这里有一个live example

答案 1 :(得分:2)

使用zip

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

答案 2 :(得分:1)

您可以使用老式的for循环:

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

答案 3 :(得分:1)

尝试一下:

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)

注意:向后迭代以获得预期的答案。

答案 4 :(得分:0)

使用列表推导的单行代码。

从零开始到最后一个索引进行迭代,然后进行减法。

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

答案 5 :(得分:0)

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

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