Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group items of a list with a step size python?

Given an input list

 l = [1 2 3 4 5 6 7 8 9 10]

and group size grp and step step

grp = 3; step = 2

I would like return a list. Note the repetition at the end

1 2 3
3 4 5
5 6 7
7 8 9
9 10 1

or if

grp= 4; step = 2

The output should be

1 2 3 4
3 4 5 6
5 6 7 8
7 8 9 10

This is the code I came up with it does not do the cyclic thing. But would like to know if there is a smaller or a simpler solution

def grouplist(l,grp,step):
    oplist = list()
    for x in range(0,len(l)):
        if (x+grp<len(l)):
        oplist.append(str(l[x:x+grp]))
    return oplist
like image 217
Arsenal Fanatic Avatar asked Dec 18 '15 15:12

Arsenal Fanatic


People also ask

How do I group a list of values in python?

Use a list comprehension to group a list by values. Use the list comprehension syntax [list[1] for list in list_of_lists] to get a list containing only the second element from each list in list_of_lists . Call set(list) with list as the previous result to remove any duplicate elements from list .

How do you group data in a list?

To group data in a list in Excel: Select the rows or columns you wish to group. On the Data tab, in the Outline group, click the Group command. In the Group dialog box, select Rows or Columns and click OK .

What is step size in python?

Step Size specifies with element to pick while indexing. So a step size of 1 tells python to pick every element, a step size of 2 means pick alternate elements, and so on. Of course, if you leave start_index and end_index blank, python assumes its 0 and len(my_list).


1 Answers

You can take advantage of the step function in xrange or range depending on what version of python you are using. Then to wrap back around just mod by the length of the list like so

import sys

def grouplist(l,grp,step):
    newlist=[]
    d = len(l)
    for i in xrange(0,len(l),step):
        for j in xrange(grp):
            newlist.append(l[(i+j)%d])
            sys.stdout.write(str(l[(i+j)%d]) + ' ')
        print

l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print grouplist(l,3,2)
1 2 3 
3 4 5 
5 6 7 
7 8 9 
9 10 1 
[1, 2, 3, 3, 4, 5, 5, 6, 7, 7, 8, 9, 9, 10, 1]

print grouplist(l,4,2)
1 2 3 4 
3 4 5 6 
5 6 7 8 
7 8 9 10 
9 10 1 2
[1, 2, 3, 4, 3, 4, 5, 6, 5, 6, 7, 8, 7, 8, 9, 10, 9, 10, 1, 2] 
like image 189
SirParselot Avatar answered Nov 14 '22 21:11

SirParselot