社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

将python列表拆分为子列表

lpt • 3 年前 • 1260 次点击  

我有一个列表,我想分成多个子列表

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']
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/127910
 
1260 次点击  
文章 [ 3 ]  |  最新文章 3 年前
jiaqi liu
Reply   •   1 楼
jiaqi liu    3 年前
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)
Sadra Naddaf
Reply   •   2 楼
Sadra Naddaf    3 年前

无其他库,并返回列表列表:

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']
Andrej Kesely
Reply   •   3 楼
Andrej Kesely    3 年前

尝试 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']