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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With