例如测试列表:
test_list = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b', 'a', 'a']
对于这个例子,我需要使用什么工具或算法来获得最大序列数:
'a' = 3
'b' = 2
'c = 1
最佳答案
使用 dict
来跟踪最大长度,并且 itertools.groupby
按连续值对序列进行分组:
from itertools import groupby
max_count = {}
for val, grp in groupby(test_list):
count = sum(1 for _ in grp)
if count > max_count.get(val, 0):
max_count[val] = count
演示:
>>> from itertools import groupby
>>> test_list = ['a', 'a', 'a', 'b', 'b', 'a', 'c', 'b', 'a', 'a']
>>> max_count = {}
>>> for val, grp in groupby(test_list):
... count = sum(1 for _ in grp)
... if count > max_count.get(val, 0):
... max_count[val] = count
...
>>> max_count
{'a': 3, 'c': 1, 'b': 2}
关于Python,使用列表,找到最大序列长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24410836/