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
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 .
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 .
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).
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With