2

I have a list:

 l = [2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 12.0,96.0, 192.0, 480.0, 360.0, 504.0, 300.0]

I want to group the elements in list in group size difference of 10. (i.e, 0-10,10-20,20-30,30-40...etc)

For eg:

Output that I'm looking for is:

[ [2,4,5,6,7,8,10],[12],[96],[192],[300],[360],[480],[504] ]

I tried using:

list(zip(*[iter(l)] * 10))

But getting wrong answer.

Sociopath
  • 13,068
  • 19
  • 47
  • 75
Shubham R
  • 7,382
  • 18
  • 53
  • 119

5 Answers5

5

Use itertools.groupby to group together after dividing(//) it by 10

from itertools import groupby
l = [2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 12.0,96.0, 192.0, 480.0, 360.0, 504.0, 300.0]

groups = []
for _, g in groupby(l, lambda x: (x-1)//10):
    groups.append(list(g))      # Store group iterator as a list

print(groups)

Output:

[[2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0], [12.0], [96.0], [192.0], [480.0], [360.0], [504.0], [300.0]] 
Sociopath
  • 13,068
  • 19
  • 47
  • 75
1

A defaultdict might not be bad for this, it's not in one pass, but you can sort the keys to keep everything in place. The integer divide by 10 will bin everything for you

groups = defaultdict(list)

for i in l:
    groups[int((i-1)//10)].append(i)

groups_list = sorted(groups.values())
groups_list[[2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0], [12.0], [96.0], [192.0], [300.0], [360.0], [480.0], [504.0]]
Ena
  • 3,481
  • 36
  • 34
C.Nivs
  • 12,353
  • 2
  • 19
  • 44
0

Even though, an answer is accepted, here is another way :

l = [2.0, 4.0, 5.0, 6.0, 7.0, 8.0, 10.0, 12.0,96.0, 192.0, 480.0, 360.0, 504.0, 300.0]
l1 = [int(k) for k in l]
l2 = list(list([k for k in l1 if len(str(k))==j]) for j in range(1,len(str(max(l1))) +1))

OUTPUT :

l2 = [[2, 4, 5, 6, 7, 8], [10, 12, 96], [192, 480, 360, 504, 300]]
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56
0

It can be sub listed using dictionary : the key for dict will be value-1/10 if same key comes value will be appended:

gd={}
for i in l:
    k=int((i-1)//10)
    if k in gd:
        gd[k].append(i)
    else:
        gd[k]=[i]
print(gd.values())
Pradeep Pandey
  • 307
  • 2
  • 7
0

You can loop over you list l and create a new list using extend and an if condition:

smaller_list = []
larger_list = []
desired_result_list = []

for element in l:
    if element <= 10:
    smaller_list.extend([element])
else:
    larger_list.append([element])

desired_result_list.extend(larger_list + [smaller_list])
DataBach
  • 1,330
  • 2
  • 16
  • 31