簡體   English   中英

將列表分組為子列表,由python中的字母元素分隔

[英]grouping a list into sublists, breaked by alphabet elements in python

我在python中有一個混合的列表:有些元素是數字,有些是字母。

例如: l = ['999','123','hello','222','333','444','bye']

我想將此列表拆分為由所有字母元素分隔的列表:

['999','123','hello'], ['222','333','444','bye']

對於['hello', '123', 'test', 'test', '456', 'test', '789'] ,輸出為: ['hello'],['123','test'],['test'],['456','test'],['789']

每個元素都是字母或數字。

這樣做的最Python方式是什么?

output = []
for i in l:
    if not output or output[-1][-1].isalpha():
        output.append([i])
    else:
        output[-1].append(i)

這樣:

l = ['999','123','hello','222','333','444','bye']

output將變為:

[['999', '123', 'hello'], ['222', '333', '444', 'bye']]

或搭配:

l = ['hello', '123', 'test', 'test', '456', 'test', '789']

output將變為:

[['hello'], ['123', 'test'], ['test'], ['456', 'test'], ['789']]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM