开发者

Best way in Python to combine 2 lists and return a min / max of a set

I currently have two set lists that combine "steps" and "time":

step = 1,1,1,1,2,2,2,2
time = 1,2,5,6,1,3,5,6

These values directly correlate, meaning a tuple looking like [(1,1),(1,2),(1,5),(1,6),(2,1),(2,3),(2,5),(2,11)]

Basically I'm trying to find the max value for step 1, and the min value of step one, as well as min/max for step 2

minstep1 = 1
maxstep1 = 6
minstep2 = 1
maxstep2 = 11

how can I accomplish this in python? do i need to create a multidimensional list? is there a function that can iterate keyvalue pairs of a tuple t开发者_JS百科hat I can just use the zip function?

Thanks!


You're looking for itertools.groupby. Here is some example code for your question:

step = 1,1,1,1,2,2,2,2
time = 1,2,5,6,1,3,5,6

from itertools import groupby, izip
from operator import itemgetter

for key, group in groupby(izip(step, time), itemgetter(0)):
    group = [item[1] for item in group]
    print 'Step:', key, 'Min:', min(group), 'Max:', max(group)

It groups time by step then finds the min and max for each group. Alternatively, you could do something like:

step.reverse()
for key, group in groupby(time, lambda _: step.pop()):
    group = tuple(group)
    print 'Step:', key, 'Min:', min(group), 'Max:', max(group)

To group by step without zipping with time.


How about this approach?

step = [1,1,1,1,2,2,2,2]
time = [1,2,5,6,1,3,5,6]

from collections import defaultdict
dd = defaultdict(set)

for s,t in zip(step, time):
    dd[s].add(t)

for k,v in dd.iteritems():
    print "step %d  min: %d max: %d" %(k, min(v), max(v))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜