python - 计算列表中第一次连续重复有多少个
问题描述
例如,我的列表是 l=[1113213211] 并且我希望程序在第一次连续重复中打印有多少“字符”,我说是因为它们是第一个但它可以是任何数字。例如,如果列表是 l=[1113213211] 我希望我的程序打印:有 3 个然后 1 个 3 然后 1 个 2 然后 1 个 然后 1 个 3 然后 1 个 2 然后 2 个。我怎样才能在 Python3 中做到这一点?
PS 我之前提到的那个列表可能会有所不同。它可以是 l=[12325228961112333] 或其他东西。
解决方案
你可以使用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
推荐阅读
- sql - SQL 提取以特定字符开头的字符串
- wagtail - PageQuerySet 上的过滤(由 specific() 重新调整)在 Wagtail 中返回 FieldError
- python - 将 python 脚本编译为 C 时如何修复 Cython 标头错误
- angularjs - 无法从 Javascript 设置 Angular 模型
- blockchain - 如何限制某人在 1 个钱包中可以拥有的资产数量?
- apache-spark - 如果我们使用 newSession() 方法创建多个 Spark Session,多个 Spark 会话之间如何共享驱动程序内存
- python - 无法在 python3 和 ImportError 中导入 tensorflow:此包不应在 Python 3 上访问
- kotlin - 减少/收集`列表
- python - 比较两个字典的键并使用与另一个字典中的键不匹配的键、值对创建一个字典 - Python
- python - 我可以将我安装的第三方 Python 包发送给其他人吗?