Search code examples
pythonlistsplitdelimiter

Python groupby to split list by delimiter


I am pretty new to Python (3.6) and struggling to understand itertools groupby. I've got the following list containing integers:

    list1 = [1, 2, 0, 2, 3, 0, 4, 5, 0]

But the list could also be much longer and the '0' doesn't have to appear after every pair of numbers. It can also be after 3, 4 or more numbers. My goal is to split this list into sublists where the '0' is used as a delimiter and doesn't appear in any of these sublists.

    list2 = [[1, 2], [2, 3], [4, 5]]

A similar problem has been solved here already: Python spliting a list based on a delimiter word Answer 2 seemed to help me a lot but unfortunately it only gave me a TypeError.

    import itertools as it

    list1 = [1, 2, 0, 2, 3, 0, 4, 5, 0]

    list2 = [list(group) for key, group in it.groupby(list1, lambda x: x == 0) if not key]

    print(list2)

File "H:/Python/work/ps0001/example.py", line 13, in list2 = [list(group) for key, group in it.groupby(list, lambda x: x == '0') if not key]

TypeError: 'list' object is not callable

I would appreciate any help and be very happy to finally understand groupby.


Solution

  • You were checking for "0" (str) but you only have 0 (int) in your list. Also, you were using list as a variable name for your first list, which is a keyword in Python.

    from itertools import groupby
    
    list1 = [1, 2, 0, 2, 7, 3, 0, 4, 5, 0]
    list2 = [list(group) for key, group in groupby(list1, lambda x: x == 0) if not key]
    
    print(list2)
    

    This should give you:

    [[1, 2], [2, 7, 3], [4, 5]]