python - 如何计算连续数列的实例数及其频率?
问题描述
我在变量中有一些文本,raw_text
我想像124
Python 一样计算连续数字序列的数量。我将如何做到这一点?
另外,有没有一种有效的方法来计算每个数列的频率?
解决方案
您可以使用正则表达式来匹配数字序列。匹配的数量将是连续数字序列的计数。
Acollections.Counter
将是获取每个匹配项的频率的便捷方法。
from collections import Counter
import re
raw_text = "blah123 hello9832 then32233 123"
matches = re.findall(r"\d+", raw_text)
print(f"found {len(matches)} number sequences")
counter = Counter(matches)
print(counter)
输出
found 4 number sequences
Counter({'123': 2, '9832': 1, '32233': 1})
使用数字序列的字典顺序按频率对结果进行排序并打破平局:
sorted_by_freq = sorted(counter.items(), key=lambda item: (-item[1], item[0]))
print(sorted_by_freq)
输出
[('123', 2), ('32233', 1), ('9832', 1)]
推荐阅读
- c# - 为什么使用 wm_settext 发送消息不起作用?
- azure-active-directory - 如何在 Angular 的 MSAL 客户端登录中提供重定向体验?
- mysql - HAProxy 无法连接到 MariaDB
- swift - Swift 如何停止 Netflix 应用程序录制,在 plist 应用程序录制限制
- oop - Lua OOP 类的多个实例被忽略,为什么?
- visual-studio - MSBuild 重新扩展属性
- c++ - 在 chromium 中添加自定义 c++ 函数并在浏览器中调用它们
- spring - SpringCloud 2020.0.2 升级产生测试错误
- java - 检查某个日期是否在前几天的几个月之后
- firebase - 在 Flutter 中使用 Firebase 存储在容器中显示图像?