Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform an action over 2 and 2 elements in a list

Tags:

python

I have a list of numbers, say

data = [45,34,33,20,16,13,12,3]

I'd like to compute the difference between 2 and 2 items, (that is, for the above data I want to compute 45-34,33-20,16-13 and 12-3, what's the python way of doing that ?

Also, more generally, how should I apply a function to 2 and 2 of these elements, that is, I want to call myfunc(data[0],data[1]),myfunc(data[2],data[3]) and so on over the list.

like image 863
Anonym Avatar asked Aug 06 '10 09:08

Anonym


People also ask

How do you run an action on each item in a list Python?

The best way to apply a function to each element of a list is to use the Python built-in map() function that takes a function and one or more iterables as arguments. It then applies the function to each element of the iterables.

How do you check if an element appears twice in a list?

Check if list contains duplicates using list.If count > 1 then it means this element has duplicate entries.


1 Answers

Try slicing the list:

from itertools import izip
[myfunc(a, b) for a, b in izip(data[::2], data[1::2])]

or you can use the fact that izip guarantees the order in which it consumes its arguments:

idata = iter(data)
[myfunc(a, b) for a, b in izip(idata, idata)]
like image 88
Duncan Avatar answered Oct 31 '22 00:10

Duncan