Skip to content Skip to sidebar Skip to footer

Index Lists For Specific Repeating Element

How do I create a new list containing only the beginning index number of where the segment of True elements consecutively repeat? main_list = [True, True, False, False, True, True

Solution 1:

This should work:

main_list= [True, True, False, False, True, True, True, True, True, False]

start_true=-1last_added=-1true_index= []

fori,valueinenumerate(main_list):if value:ifstart_true==-1:start_true=ielse:ifstart_true!=last_added:true_index.append(start_true)last_added=start_trueelse:start_true=-1print(true_index)

Also if you want the code to detect consecutive Trues including a single True here is a version that does that:

main_list= [True, False, False]

start_true=-1last_added=-1true_index= []

fori,valueinenumerate(main_list):if value:ifstart_true==-1:start_true=iifstart_true!=last_added:true_index.append(start_true)last_added=start_trueelse:start_true=-1print(true_index)

Solution 2:

The following is a much shorter and solution, and might be preferable -

main_list = [True, True, False, False, True, True, True, True, True, False]

defmy_diff(my_list):
    return [1if my_list[0] else0] + [y - x for x, y inzip(my_list[:-1], my_list[1:])]

solution = [i for i, x inenumerate(my_diff(main_list)) if x == 1]

print(solution)
# [0, 4]

Explanation: I'd personally solve this by using np.diff, and simply searching for the "transitions" (from False to True). But seeing as numpy is out of scope, I've just implemented a simple diff function, and the beginning of a sequence of Trues is the same as having a difference of 1 between two consecutive elements. And to make sure the first element isn't missed, if it's True then it's by definition the beginning of a sequence, and so we plant a 1 in place. Otherwise we don't :-).

To sum things up - look for "element - prev-element" being equal 1.

Post a Comment for "Index Lists For Specific Repeating Element"