1

Im trying to find the index of each 1 that is at the end of each group(sequence) of 1s. The output for the example below should be [17, 12, 9, 5, 1].

I can find the 1 at index 17 using the formula below but I also need to find the 1 at index 12. (i.e. it's the last instance of 1 in each sequence (or group) of 1s)

list = [1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0] index_list1 = [i for i, v in enumerate(list) if v == 1] index_list0 = [i for i, v in enumerate(list) if v == 0] val1 = None for i in index_list1[::-1]: if i < index_list0[-1]: val1 = i break else: val1 = index_list1[-1] if val1 is not None: index1 = val1 
0

1 Answer 1

1

You can simply use a conditional list comprehension:

my_list = [1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0] results = [i for i, value in enumerate(my_list) if value == 1 and (my_list+[0])[i+1] != 1] print(results) 

this will print

[1, 5, 9, 12, 17] 

The reason to append a [0] is to take care of cases where the original list ends with a 1.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.