简体   繁体   English

计算列表中第一次连续重复有多少个

[英]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.例如,我的列表是 l=[1113213211] 并且我希望程序打印第一个连续重复的“字符”有多少个,我说一个是因为它们是第一个,但它可以是任何数字。 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.例如,如果列表是 l=[1113213211] 我希望我的程序打印:有 3 个,然后是 1 个,然后是 1 个,然后是 1 个,然后是 1 个,然后是 1 个,然后是 1 个,然后是 2 个。 How can I do that in Python3?我怎样才能在 Python3 中做到这一点?

PS That list I mentioned before can be different. PS 我之前提到的那个列表可能会有所不同。 It can be l=[12325228961112333] or something else.它可以是 l=[12325228961112333] 或其他东西。

You could use itertools.groupby like,你可以使用itertools.groupby类的,

>>> 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: itertools groupby 是为这项工作制作的:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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