Need to find indices very similar to here
But I have a list of multiple groups of incrementing values, eg lst = [0,1,2,7,8,9]
Expected output: [0,3]
Version with a simple loop:
lst = [0,1,2,7,8,9]
prev = float('-inf')
out = []
for i,v in enumerate(lst):
if v!=prev+1:
out.append(i)
prev = v
out
Same thing with a list comprehension and zip
:
out = [i for i, (a,b) in enumerate(zip([float('-inf')]+lst, lst)) if a+1!=b]
Variant with itertools.pairwise
(python ≥3.10):
from itertools import pairwise
out = [0]+[i for i, (a,b) in enumerate(pairwise(lst), start=1) if a+1!=b]
output: [0, 3]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.