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 = -1
last_added = -1
true_index = []

for i, value in enumerate(main_list):
    if value:
        if start_true == -1:
            start_true = i
        else:
            if start_true != last_added:
                true_index.append(start_true)
                last_added = start_true
    else:
        start_true = -1
        
print(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 = -1
last_added = -1
true_index = []

for i, value in enumerate(main_list):
    if value:
        if start_true == -1:
            start_true = i
        if start_true != last_added:
            true_index.append(start_true)
            last_added = start_true
    else:
        start_true = -1
        
print(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]

def my_diff(my_list):
    return [1 if my_list[0] else 0] + [y - x for x, y in zip(my_list[:-1], my_list[1:])]

solution = [i for i, x in enumerate(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"