python - Detect consecutive identical values in list -
i have dataset organized dictionary of lists, like:
{ 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] } i want detect cases of consecutive identical values (esp. 0's), in particular detecting instances of n consecutive identical values.
for example, if n 3 , value 0, append uuid of first key:value pair list of qualifying uuids, not second.
what's efficient way detect consecutive identical values in way?
use itertools.groupby detect runs of consecutive numbers:
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]} itertools import groupby def detect_runs_in_dict(d, n=3): return [uuid uuid, val in d.items() #in python 2, use .iteritems if any(len(list(g)) >= n k,g in groupby(val))] demo
detect_runs_in_dict(uuids) out[28]: ['a'] detect_runs_in_dict(uuids,n=2) out[29]: ['a', 'b'] this doesn't discriminate on value can in "runs" - if want specify it, that's straightforward add:
def detect_runs_in_dict(d, n=3, searchval=0): return [uuid uuid, val in d.items() if any(k == searchval , len(list(g)) >= n k,g in groupby(val))]
Comments
Post a Comment