Godpoong
Godpoong

Reputation: 25

Is there better way to check value changed in sequence?

I have a list like below:

list = ['A', 'A', 'B', 'A', 'B', 'A', 'B']

And, I want to count the number of the first value (in case above, 'A') consecutively before the other values ('B') come.

So I wrote a code like:

history = list[0]
number_A = 0
number_B = 0
for i in list:
    if history != i:
        break

    if i == 'A':
        number_A += 1
        history = 'A'
    else:
        number_B += 1
        history = 'B'

However, I think this is very untidy. Is there any more simple way to do this process?

Thank you for reading.

Upvotes: 1

Views: 307

Answers (4)

Mad Wombat
Mad Wombat

Reputation: 15105

There is no reason for the "else" clause, you are not going to count 'B's since you are going to break before you get there.

lst = ['A', 'A', 'B', 'A', 'B', 'A', 'B']

count = 0

for i in lst:
    if i != lst[0]:
        break
    count += 1

print("list starts with %d of %s's" % (count, lst[0]))

Upvotes: 3

actual_panda
actual_panda

Reputation: 1260

I renamed your list to lst in order to not override the builtin name list.

>>> lst = ['A', 'A', 'B', 'A', 'B', 'A', 'B']
>>> string = ''.join(lst)
>>> len(string) - len(string.lstrip('A'))
2

Upvotes: 1

Patrick Haugh
Patrick Haugh

Reputation: 60994

Using groupby with the default key function, you can count the number of items in the first grouper:

from itertools import groupby

def count_first(lst):
    if not lst:
        return 0
    _, grouper = next(groupby(lst))
    return sum(1 for _ in grouper)

print(count_first(['A', 'A', 'B', 'A', 'B', 'A', 'B']))  
# 2

Upvotes: 5

RoyM
RoyM

Reputation: 747

You could use takewhile:

from itertools import takewhile

my_list = ['A', 'A', 'B', 'A', 'B', 'A', 'B']

res = takewhile(lambda x: x == my_list[0], my_list)
print(len(list(res)))

OUT: 2

Upvotes: 2

Related Questions