-1

How can I "pack" consecutive duplicated elements in a list into sublists of the repeated element?

What I mean is:

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

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


For removing the duplicates instead of packing them, see Removing elements that have consecutive duplicates

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Tanmay
  • 69
  • 9

3 Answers3

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, 4, 4, 1]
print(pack(l))

Or one-line:

l = [1, 1, 1, 2, 2, 3, 4, 4, 1]
result = [list(group) for key,group in groupby(l)]
# [[1, 1, 1], [2, 2], [3], [4, 4], [1]]
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
1

You can use:

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

# bootstrap: initialize a sublist with the first element of lst
out = [[lst[0]]]
for it1, it2 in zip(lst, lst[1:]):
    # if previous item and current one are equal, append result to the last sublist
    if it1 == it2:
        out[-1].append(it2)
    # else append a new empty sublist
    else:
        out.append([it2])

Output:

>>> out
[[1, 1, 1], [2, 2], [3], [4, 4], [1]]
Corralien
  • 109,409
  • 8
  • 28
  • 52
0

This code will do:

data = [0,0,1,2,3,4,4,5,6,6,6,7,8,9,4,4,9,9,9,9,9,3,3,2,45,2,11,11,11]
newdata=[]
for i,l in enumerate(data):
    if i==0 or l!=data[i-1]:
        newdata.append([l])
    else:
        newdata[-1].append(l)

#Output
[[0,0],[1],[2],[3],[4,4],[5],[6,6,6],[7],[8],[9],[4,4],[9,9,9,9,9],[3,3],[2],[45],[2],[11,11,11]]
atteggiani
  • 94
  • 4