Toi
Toi

Reputation: 137

Sperate the list based on a value in python

I have a list like below:-

list1 = ['box','ball','new','bat','chess','old']

I want to split this list based on values. In the above list, I want to insert the values before 'new' into a new list and the values before 'old' have to be inserted into a new list. The values before 'new' and 'old' can be one or more but here it has two values. I tried using split_after but I am getting the below result:-

from more_itertools import split_after

list1 = ['box','ball','new','bat','chess','old']
list(split_after(list1, lambda x: x == "new"))

Result:-

[['box', 'ball', 'new'], ['bat', 'chess', 'old']]

But desire output:-

result1 = ['box', 'ball']
result2 = ['bat', 'chess']

Upvotes: 2

Views: 57

Answers (3)

KnowledgeGainer
KnowledgeGainer

Reputation: 1097

If the values are more based on which you have to split like new and old, you can do this:

list1 = ['box','ball','new','bat','chess','old']
split_val = ['new','old'] # Based on these values you can separate list. You can add more values here.

new_list=[]
k=0
for i in split_val:
    for j in range(len(list1)):
        if list1[j]==i and j!=0:
            new_list.append(list1[k:j])
            k=j+1

new_list.append(list1[k:])
new_list = [i for i in new_list if len(i)>0]
print(new_list)

Output:

[['box', 'ball'], ['bat', 'chess']]

Upvotes: 1

Andrej Kesely
Andrej Kesely

Reputation: 195408

Another solution, using standard itertools.groupby:

list1 = ["box", "ball", "new", "bat", "chess", "old"]

from itertools import groupby

out = [
    list(g) for v, g in groupby(list1, lambda k: k in {"new", "old"}) if not v
]
print(out)

Prints:

[['box', 'ball'], ['bat', 'chess']]

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163207

You might use split_at, and in the lambda check for either new or old.

Then remove the empty lists from the result.

from more_itertools import split_at

list1 = ['box', 'ball', 'new', 'bat', 'chess', 'old']
print(list(filter(None, split_at(list1, lambda x: x == "new" or x == "old"))))

Output

[['box', 'ball'], ['bat', 'chess']]

Upvotes: 2

Related Questions