简体   繁体   中英

count how many ones are in first consecutive repetition in list

For example my list is l=[1113213211] and I want the program to print how many "characters" are in first consecutive repetition of ones, I say ones because they are the the first but it can be any number. For example if list is l=[1113213211] I want my program to print: there are 3 ones then 1 three then 1 two then 1 one then 1 three then 1 two then 2 ones. How can I do that in Python3?

PS That list I mentioned before can be different. It can be l=[12325228961112333] or something else.

You could use itertools.groupby like,

>>> x = [1113213211]
>>> import itertools
>>> g = itertools.groupby(''.join(str(v) for v in x))
>>> for k,grp in g:
...   print(f'{k} is present {len(list(grp))} times consequitively')
... 
1 is present 3 times consequitively
3 is present 1 times consequitively
2 is present 1 times consequitively
1 is present 1 times consequitively
3 is present 1 times consequitively
2 is present 1 times consequitively
1 is present 2 times consequitively

What you want is to iterate over the number and check if it is the same as the last one and do something accordingly. The following code should do it:

number = 1113213211 
number = [int(d) for d in str(number)] # split number into digits

list = [] # to store lists that represent (number, times seen)
lastSeen = None
for i in number: # iterate over all digits
    if lastSeen == None: # initial case
        lastSeen = [i,1]
    else:
        if i == lastSeen[0]: # if the same: add 1
            lastSeen[1] +=1
        else: # if not the same, add it to the list 
            list.append(lastSeen)
            lastSeen = [i,1]
print (list)
# [[1, 3], [3, 1], [2, 1], [1, 1], [3, 1], [2, 1]]

itertools groupby was made for this job:

from itertools import groupby

x = [1,1,1,1,2,2,2,3,3,2,2,1,1]
[(k,len(list(g))) for k,g in groupby(x)]

[(1, 4), (2, 3), (3, 2), (2, 2), (1, 2)]

Was this the sort of thing you were looking for?

l = '12325228961112333'


def count_characters(s):
    answer = "There are "
    count = 0
    character = s[0]
    for ch in s:
        if(ch == character):
            count += 1
        else:
            answer += ("{} {}s ").format(count, character)
            character = ch
            count = 1
    answer += ("{} {}s ").format(count, character)
    return answer


print(count_characters(l))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM