0

I have a array (list) with times and now I need to determine if the eclipsed time is between two successive times from this list.

duurSeq=[11,16,22,29]
nu = time.time()
verstreken_tijd = nu - starttijd
for t in duurSeq:
   if (verstreken_tijd > t ) and (verstreken_tijd < **t_next** ):
      doSomething():

my question is: How do I get t_next (the next item in the array within the for loop)

SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
Richard de Ree
  • 2,329
  • 4
  • 30
  • 47

4 Answers4

2

Try this,

duurSeq=[11,16,22,29]
for c, n in zip(duurSeq, duurSeq[1:]):
    if (verstreken_tijd > c) and (verstreken_tijd < n):
        doSomething():

Refer to Iterate a list as pair (current, next) in Python for a general approach.

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

# Demo
l = [11, 16, 22, 29]
for c, n in pairwise(l):
    print(c, n)

# Output
(11, 16)
(16, 22)
(22, 29)
Community
  • 1
  • 1
SparkAndShine
  • 17,001
  • 22
  • 90
  • 134
0

Sounds like you need some pointer arithmetic. See here for a great example.

TL/DR you can move to the next item in the array by telling the interpreter to move 1 block up the sizeof(int). Basically take the next integer in memory. This works only because you know the size of the elements in the array.

Community
  • 1
  • 1
0

Use a foor loop on index instead of element

duurSeq = [11,16,22,29]
nu = time.time()
verstreken_tijd = nu - starttijd

for t in range(len(duurSeq)-1):
   if verstreken_tijd > duurSeq[i] and verstreken_tijd < duurSeq[i+1]:
      doSomething():
Julien Goupy
  • 165
  • 6
0

Looks like you want to access index of array inside for loop.

for index, element in enumerate(duurSeq):
    # Use duurSeq[index] to access element at any position
Gaurav Kumar
  • 1,091
  • 13
  • 31