Tiger1
Tiger1

Reputation: 1377

How to group close distant items by multiples of an integer

My goal is to group the list below by multiples of 7 (ie 7,14,21)

mylist=[1,3,7,8,10,14,15,19,22]

Ideal result:[(1,3,7),(8,10,14),(15,19),(22)]

My attempt:

>>>groups=[]
>>> for x in itertools.groupby(mylist,lambda x: x<=range(7,49,7)):
             groups.append(x)
>>> groups
[(True, <itertools._grouper object at 0x0000000002EBC128>)]

Any ideas on how to arrive at the ideal result? Thanks.

Upvotes: 1

Views: 54

Answers (3)

Vijay Kumar
Vijay Kumar

Reputation: 345

I think this code help you:

if __name__ == '__main__':
    a = [1,3,7,8,10,14,15,19,22]
    b = []
    c = set()
    for i in a:
        x = i/7
        if i%7 == 0:
            x -= 1
        b.append(x)
        c.add(x)
    c = list(c)
    a.sort()
    res = []
    for i in c:
        res.append(b.count(i))
    count = 0
    for i in res:
        print a[count:count+i]
        count += i

Upvotes: -1

carlosdc
carlosdc

Reputation: 12152

jonrsharpe gives an excellent solution. This alternative is universal (not necessarily Python-specific) and correct for obvious reasons:

groups = []
l = [1,3,7,8,10,14,15,19,22]
a = 0
sublist = []
for item in l:
    if 7*a<item and item<=7*(a+1):
        sublist.append(item)
    else:
        groups.append(tuple(sublist))
        a = item/7 
        sublist = [item]

if sublist:
    groups.append(tuple(sublist))

Upvotes: 2

jonrsharpe
jonrsharpe

Reputation: 122066

You can use:

itertools.groupby(mylist, lambda x: (x - 1) // 7)

Your current attempt compares each item to the range object, not the values it produces. This makes no sense, and is a TypeError in Python 3.x.

To unpack the groupby object to a list of tuples:

list(map(lambda g: tuple(g[1]), itertools.groupby(...)))

Upvotes: 2

Related Questions