简体   繁体   中英

Python Subtracting Elements in a Lists from Previous Element

I have a loop that produces multiple lists such as these:

  [1,6,2,8,3,4]

  [8,1,2,3,7,2]

  [9,2,5,6,1,4]

For each list, I want to subtract the first two elements, and then use that value to then subtract the third element from.

For example, the first list should end up looking like:

  [-5, 4,-6, 5,-1]

I have tried to manually do this, but there are too many lists to do this and it would take too much time.

How would I do that in the least amount of lines of code?

From your updated example, it seems like, given a list [a, b, c, d, ...] you want [ab, bc, cd, de, ...] as a result. For this, you should zip the list with itself, offset by one position, and subtract the elements in the pairs.

lst = [1,6,2,8,3,4]
res = [x-y for x, y in zip(lst, lst[1:])]    
print(res)  # [-5, 4, -6, 5, -1]

If the lists are much longer, you might instead create an iterator, use tee to duplicate that iterator, and advance one of the iterators one position with next :

import itertools    
i1, i2 = itertools.tee(iter(lst))
next(i2)
res = [x-y for x, y in itertools.izip(i1, i2)]  # or just zip in Python 3
>>> my_list = [1,6,2,8,3,4]
>>> [my_list[i] - my_list[i+1] for i in range(len(my_list) -1)]
[-5, 4, -6, 5, -1]

If I understand you correctly, you want to optimize your code, so it runs faster. Reducing the lines of code wont improve this since you are looping through lists.

From what I can tell, your problem can't be solved in under n-1 subtractions (where n is the number of input values). However there might be a more effective solution if you know how the lists are created.

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