简体   繁体   English

如何在Python 3中的列表中向后减去?

[英]How to subtract backwards in a list in Python 3?

I am trying to subtract a list backwards in Python. 我试图在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. 减法应如下所示:索引1-索引0,索引2-索引1,依此类推。 This is the output: 这是输出:

1
3
2
2
76

How can i do something like this using Python 3? 我如何使用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: 使用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))

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循环:

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中连续数字的差。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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