首页 > 解决方案 > 计算列表中第一次连续重复有多少个

问题描述

例如,我的列表是 l=[1113213211] 并且我希望程序在第一次连续重复中打印有多少“字符”,我说是因为它们是第一个但它可以是任何数字。例如,如果列表是 l=[1113213211] 我希望我的程序打印:有 3 个然后 1 个 3 然后 1 个 2 然后 1 个 然后 1 个 3 然后 1 个 2 然后 2 个。我怎样才能在 Python3 中做到这一点?

PS 我之前提到的那个列表可能会有所不同。它可以是 l=[12325228961112333] 或其他东西。

标签: pythonlistmethodscount

解决方案


你可以使用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

推荐阅读