Home > other >  Split a list into sublists based on the value of an element?
Split a list into sublists based on the value of an element?

Time:11-04

If I have a list of elements:

foo = ["Bob", 14, 20, "Sam", "Bob", 15, 23, "Bob", "Jim", 14]

I want to split this list such that they are split by the element "Bob".

How can I split it such that the output is:

[["Bob", 14, 20, "Sam"], ["Bob", 15, 23], ["Bob", "Jim", 14]]

Assume that the list can be much larger than this but there will always been some elements called "Bob".

CodePudding user response:

Here's one way to do it:

>>> foo = ["Bob", 14, 20, "Sam", "Bob", 15, 23, "Bob", "Jim", 14]
>>> 
>>> x = [i for i, s in enumerate(foo) if s == "Bob"]
>>> y = x[1:]   [len(foo)]
>>> z = [foo[i:j] for i, j in zip(x, y)]
>>>
>>> z
[['Bob', 14, 20, 'Sam'], ['Bob', 15, 23], ['Bob', 'Jim', 14]]
>>> 

If the list doesn't start with 'Bob', it will skip the elements that precede the first 'Bob', so if you want those then you'd need to add a check for that.

CodePudding user response:

This is one simple approach.

We test each item in foo to see if it matches "Bob" and if it does, we create a small_list to hold "Bob" and be a repository to then hold other elements that will follow after.

If the element is not (!=) "Bob" then we simply add it to the existing small_list and add the small_list to the bigger list and keep doing that, until we reach another "Bob" and start over with a new small_list.

foo = ["Bob", 14, 20, "Sam", "Bob", 15, 23, "Bob", "Jim", 14]

big_list = []
small_list = []
for item in foo:
    if item != "Bob":
        small_list.append(item)
    elif item == "Bob":
        small_list = [item]
        big_list.append(small_list)

CodePudding user response:

Using extend with an iterator on the output list can perform the grouping:

foo = ["Bob", 14, 20, "Sam", "Bob", 15, 23, "Bob", "Jim", 14]

bar = []
bar.extend([x] for x in foo if x=='Bob' or bar[-1].append(x))

print(bar)
[['Bob', 14, 20, 'Sam'], ['Bob', 15, 23], ['Bob', 'Jim', 14]]

Note that the first item of foo needs to be a 'Bob' for this to work. Otherwise you'll need to initialize bar with [[]] instead of []

  • Related