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.
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With