Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

python - 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, True, True, True, False]

The expected answer should be:

true_index = [0,4] #first repeating True starts at index 0 from main_list and the second repeating True starts at index 4 from main_list

If given a list like:

l = [True,False,False]

Expected answer would be:

index_list = [0]

I need a simple code that does not require the use of numpy or groupby. I tried dividing the main_list into sublists first containing groups of the repeating True elements, however also struggled without using numpy or groupby.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...