I have a list that I want to split into multiple sublists
acq=['A1', 'A2', 'D', 'A3', 'A4', 'A5', 'D', 'A6']
ll=[]
for k,v in enumerate(acq):
if v == 'D':
continue # continue here
ll.append(v)
print(ll)
Above solution give gives an expanded appended list, which is not what I am looking for. My desired solution is:
['A1', 'A2']
['A3', 'A4', 'A5']
['A6']
CodePudding user response:
Try itertools.groupby
:
from itertools import groupby
acq = ["A1", "A2", "D", "A3", "A4", "A5", "D", "A6"]
for v, g in groupby(acq, lambda v: v == "D"):
if not v:
print(list(g))
Prints:
['A1', 'A2']
['A3', 'A4', 'A5']
['A6']
CodePudding user response:
No additional Library, and return a list of lists:
acq=['A1', 'A2', 'D', 'A3', 'A4', 'A5', 'D', 'A6']
all_list=[]
ll=[]
for i in acq:
if i == 'D':
all_list.append(ll)
ll=[]
continue
ll.append(i)
all_list.append(ll)
print(*all_list,sep='\n')
print:
['A1', 'A2']
['A3', 'A4', 'A5']
['A6']
CodePudding user response:
acq=['A1', 'A2', 'D', 'A3', 'A4', 'A5', 'D', 'A6']
ll=[]
temp=[]
for k,v in enumerate(acq):
if v == 'D':
ll.append(temp)
temp=[]
continue # continue here
temp.append(v)
l1.append(temp)
print(ll)