首页 > 解决方案 > 如何计算连续数列的实例数及其频率?

问题描述

我在变量中有一些文本,raw_text我想像124Python 一样计算连续数字序列的数量。我将如何做到这一点?

另外,有没有一种有效的方法来计算每个数列的频率?

标签: pythonregex

解决方案


您可以使用正则表达式来匹配数字序列。匹配的数量将是连续数字序列的计数。

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

推荐阅读