-1

What I mean is :

Eg., l = [1, 1, 1, 2, 2, 3, 3, 4]
pack(l) -> [[1,1,1], [2,2], [3,3], [4]]

I want to do this problem in a very basic way as I have just started i.e using loops and list methods.I have looked for other methods but they were difficult for me to understand

Tanmay
  • 69
  • 8

2 Answers2

2

You can use groupby

from itertools import groupby

def pack(List):
    result = []
    for key,group in groupby(List):
         result.append(list(group))

    return result

l = [1, 1, 1, 2, 2, 3, 3, 4]
print(pack(l))

Or one-line:

l = [1, 1, 1, 2, 2, 3, 3, 4]
result = [list(group) for key,group in groupby(l)]
# [[1, 1, 1], [2, 2], [3, 3], [4]]

You can also use lambda to generate a function:

from itertools import groupby

l = [1, 1, 1, 2, 2, 3, 3, 4]

pack = lambda List: [list(group) for key,group in groupby(List)]
pack(l)
jizhihaoSAMA
  • 11,804
  • 9
  • 23
  • 43
  • I really appreciate this but I was talking about not using the above library.I want to use the basic approach as these things haven't been taught to us yet – Tanmay Apr 06 '20 at 14:21
  • @Tanmay So have you learned about `collections.Counter`? – jizhihaoSAMA Apr 06 '20 at 14:31
0

This will work:

l = [1, 1, 1, 2, 2, 3, 3, 4]
l2 = [[entry] * l.count(entry) for entry in set(l)]
l2 # [[1, 1, 1], [2, 2], [3, 3], [4]]
Carsten
  • 2,325
  • 1
  • 11
  • 24