Skip to content
Advertisement

Iteration numbers with True False condition

Please HELP!!

I have a list:

a = ['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']

I want to generate iteration number if it’s False the number continues and if it’s True the number stays. I Try this code:

result = []
x = 1
for i in a:
    while i == 'False':
        result.append(x)
        if i == 'True':
            x+=1
            continue
            result.append(x)
        x += 1

it’s just keep running and did not show any output. the desired output will be [1,2,3,3,3,4,5,6,6]

I have no idea what’s wrong with it Thanks

Advertisement

Answer

Yet another version of this (with the output behaving as required by OP):

def weird_sequence(some_list):
    prev = None
    number = 0
    for item in some_list:
        if prev is None:
            prev = "False"
        if item == "False" or prev == "False":
            number += 1
        yield number
        prev = item

Usage:

>>> list(weird_sequence(['False', 'False', 'True', 'True', 'True', 'False', 'False', 'True', 'True']))
[1, 2, 3, 3, 3, 4, 5, 6, 6]
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement