[英]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.