Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to crate multiple lists from another list based on condition/breakpoints in Python?

I'm looking for a way to create multiple lists from one large list.

What I want to do is to filter out different digit groups (amounts of fruits sold each week) form a list. Each group of digits should be in a separate list when it hits '******' string that indicates where each group should end.

Example list:

['apples', '1000', '2000', '2500', '******', 'oranges', '5000', '150', '******']

So far I've got this:

list = []
for i in mainList:
        if i.isdigit():
            list.append(i)
    print(list)

However, my code prints everything in one list like that:

#Ouput = ['1000', '2000', '2500', '5000', '150'] 

How can divide the output into separate lists so that each fruit group is printed in a separate "blocks" and all of them are part of a larger list?

The result I'm looking for should look like this:

[['1000', '2000', '2500'], ['5000', '150']]

So far I've tried this:

for i in mainList:
   if '******' in i:
       break
   if i != '******':
       result.append(i)

But this returns the same list and I was expecting it to break the loop at the first '******' breakpoint. I am struggling to separate each part of the list after the '******' delimiter.

I'd appreciate any help I can get.

like image 602
rootpl Avatar asked Jan 26 '23 18:01

rootpl


1 Answers

The most pythonic way I can think of is to use itertools.groupby:

from itertools import  groupby

lst = ['apples', '1000', '2000', '2500', '******', 'oranges', '5000', '150', '******']

result = [list(group) for k, group in  groupby(lst, key=str.isdigit) if k]
print(result)

Output

[['1000', '2000', '2500'], ['5000', '150']]

As an alternative you could use a for loop:

result = []
start = True
for element in lst:
    if start and element.isdigit():  # start group
        result.append([element])
        start = False
    elif element.isdigit():  # just append to current group
        result[-1].append(element)
    else:  # close group
        start = True

print(result)

Output

[['1000', '2000', '2500'], ['5000', '150']]
like image 105
Dani Mesejo Avatar answered Jan 29 '23 19:01

Dani Mesejo