gpt4 book ai didi

Python,使用列表,找到最大序列长度

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:32:22 25 4
gpt4 key购买 nike

例如测试列表:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com