Helen Che
Helen Che

Reputation: 2011

Split list into smaller lists based on values?

Say I have a list: [1, 2, 3, 4, -1, 5, 6, 7, -1, 0, 0, 3, 2, 1]

I want to split this list into using values -1 or 0, 0 as a delimiter:

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

(Note the empty 3rd list)

How would I achieve this? My current solution is just a trivial loop but I'm wondering if theres a more pythonic solution (using list comprehensions) for delimiters of any length?

Current solution as requested (messy and hacky :P)

string = '|'.join([str(x) for x in data]).replace('-1', ',').replace('0|0', ',')
buckets = [x.split('|') if y for x in string.split(',')]

Upvotes: 0

Views: 171

Answers (3)

mkHun
mkHun

Reputation: 5921

Try this

use one iteration for to do it.

ar = [1, 2, 3, 4, -1, 5, 6, 7, -1, 0, 0, 3, 2, 1]
data  = ', '.join(map(str, ar))
import re
data = re.split(", -1,| 0, 0,",data)
bucket = []
import ast
for y in data:
    hac = ast.literal_eval("["+y+"]")
    bucket.append(hac)
print bucket

Upvotes: 0

The6thSense
The6thSense

Reputation: 8335

Using simple for loop and check conditions

Code:

lst = [1, 2, 3, 4, -1, 5, 6, 7, -1, 0, 0, 3, 2, 1,-1,0]
output_lst = []
check = 0
sample=[]
for val in lst:
    if val == -1 :
        output_lst.append(sample)
        check = 0
        sample = []
        continue
    if val == 0 :       

        if check ==1 :
            output_lst.append(sample[:-1])
            check = 0
            sample = []
            continue
        check = 1
    sample.append(val)
if check ==1:
    output_lst.append(sample)
print output_lst

Output:

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

Upvotes: 0

Eugene Soldatov
Eugene Soldatov

Reputation: 10145

It's not trivial, but you can done it like this:

my_list = [1, 2, 3, 4, -1, 5, 6, 7, -1, 0, 0, 3, 2, 1]

my_list = ','.join(map(str, my_list))
my_list = [x.split(',') for y in my_list.split('0,0,') for x in y.split(',-1,')]
my_list = [map(int, x) if x != [''] else [] for x in my_list]

Upvotes: 1

Related Questions