将 python 列表拆分为子列表

splitting a python list into 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)

上面的解决方案给出了一个扩展的附加列表,这不是我要找的。我想要的解决方案是:

['A1', 'A2']
['A3', 'A4', 'A5']
['A6']

尝试 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))

打印:

['A1', 'A2']
['A3', 'A4', 'A5']
['A6']

没有额外的库,并且return列表列表:

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')

打印:

['A1', 'A2']
['A3', 'A4', 'A5']
['A6']
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)