Home > Back-end >  Loop to factor given list
Loop to factor given list

Time:02-02

I have data l:

[[Timestamp('2022-07-14 00:01:00'), Timestamp('2022-07-14 00:11:00'), 1],
 [Timestamp('2022-07-14 00:08:00'), Timestamp('2022-07-14 00:18:00'), 1],
 [Timestamp('2022-07-14 00:15:00'), Timestamp('2022-07-14 00:25:00'), 1],
 [Timestamp('2022-07-14 00:22:00'), Timestamp('2022-07-14 00:32:00'), 0],
 [Timestamp('2022-07-14 00:29:00'), Timestamp('2022-07-14 00:39:00'), 0],
 [Timestamp('2022-07-14 00:36:00'), Timestamp('2022-07-14 00:46:00'), 1],
 [Timestamp('2022-07-14 00:43:00'), Timestamp('2022-07-14 00:53:00'), 1],
 [Timestamp('2022-07-14 00:50:00'), Timestamp('2022-07-14 01:00:00'), 1],
 [Timestamp('2022-07-14 00:57:00'), Timestamp('2022-07-14 01:07:00'), 0],
 [Timestamp('2022-07-14 01:04:00'), Timestamp('2022-07-14 01:14:00'), 1],
 [Timestamp('2022-07-14 01:11:00'), Timestamp('2022-07-14 01:21:00'), 1],
 [Timestamp('2022-07-14 01:18:00'), Timestamp('2022-07-14 01:28:00'), 1],
 [Timestamp('2022-07-14 01:25:00'), Timestamp('2022-07-14 01:35:00'), 0],
 [Timestamp('2022-07-14 01:32:00'), Timestamp('2022-07-14 01:42:00'), 0]]

I need a loop to factor this data to obtain first timestamp where l[i][2] == 1 and second timestamp where l[i][2] is 1 consecutively in a row.

expected output:

Timestamp('2022-07-14 00:01:00'), Timestamp('2022-07-14 00:25:00')
...

CodePudding user response:

Try this.

start = None
end = None
for i in range(len(l)):
    if l[i][2] == 1:
        if start is None:
            start = l[i][0]
        end = l[i][1]
    elif start is not None:
        break

print(start, end)

CodePudding user response:

Should work smoothly:

results = []
start = None

for i in range(len(l)):
    if l[i][2] == 1:
        if start is None:
            start = l[i][0]
        else:
            end = l[i][1]
            results.append((start, end))
            start = None

print(results)
  • Related