Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a tuple in enumerate?

I want to iterate through a list and sum all the elements. Except, if the number is a 5, I want to skip the number following that 5. So for example:

x=[1,2,3,4,5,6,7,5,4,3] #should results in 30.

I'm just not sure how I can access the index of a tuple, when I use enumerate. What I want to do, is use an if statement, that if the number at the previous index == 5, continue the loop.

Thanks you

like image 695
Metal.days Avatar asked Dec 10 '22 05:12

Metal.days


1 Answers

The itertools documentation has a recipe for this called pairwise. You can either copy-paste the function or import it from more_itertools (which needs to be installed).

Demo:

>>> from more_itertools import pairwise
>>> 
>>> x = [1,2,3,4,5,6,7,5,4,3]
>>> x[0] + sum(m for n, m in pairwise(x) if n != 5)
30

edit:

But what if my datastructure is iterable, but does not support indexing?

In this case, the above solution needs a minor modification.

>>> from itertools import tee
>>> from more_itertools import pairwise
>>> 
>>> x = (n for n in [1,2,3,4,5,6,7,5,4,3]) # generator, no indices!
>>> it1, it2 = tee(x)
>>> next(it1, 0) + sum(m for n, m in pairwise(it2) if n != 5)
30
like image 56
timgeb Avatar answered Dec 12 '22 19:12

timgeb