gpt4 book ai didi

python - 检测列表中的连续相同值

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:04 25 4
gpt4 key购买 nike

我将数据集组织成列表字典,例如:

{ UUID: [3, 3, 5, 3, 0, 0, 3, 3, 2, 3, 2, 1, 1, 0, 2, 0, 5, 0, 0, 0, 0, 3, 4, 1, 2], 
UUID: [1, 2, 3, 1, 0, 0, 2] }

我想检测连续相同值(尤其是 0)的情况,特别是检测 n 个连续相同值的情况。

例如,如果 n 为 3 而值为 0,我会将第一个键值对的 UUID 附加到符合条件的 UUID 列表中,而不是第二个。

以这种方式检测连续相同值的最有效方法是什么?

最佳答案

使用 itertools.groupby 检测连续数字的运行:

uuids = { 'a': [3, 3, 5, 3, 0, 0, 3, 3, 2, 3, 2, 1, 1, 0, 2, 0, 5, 0, 0, 0, 0, 3, 4, 1, 2], 
'b': [1, 2, 3, 1, 0, 0, 2]}

from itertools import groupby

def detect_runs_in_dict(d, n=3):
return [uuid for uuid, val in d.items() #in python 2, use .iteritems
if any(len(list(g)) >= n for k,g in groupby(val))]

演示

detect_runs_in_dict(uuids)
Out[28]: ['a']

detect_runs_in_dict(uuids,n=2)
Out[29]: ['a', 'b']

这不会区分“运行”中的值 - 如果您想指定它,可以直接添加:

def detect_runs_in_dict(d, n=3, searchval=0):
return [uuid for uuid, val in d.items()
if any(k == searchval and len(list(g)) >= n for k,g in groupby(val))]

关于python - 检测列表中的连续相同值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22310075/

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