将列表分组为子列表,在python中由字母表元素分隔
我在python中有一个混合的列表:一些元素是数字,一些是字母 例如:将列表分组为子列表,在python中由字母表元素分隔,python,regex,string,python-3.x,list,Python,Regex,String,Python 3.x,List,我在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'
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']
每个元素都是字母或数字
最具蟒蛇式的方式是什么
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']
输出将变为:
[['999', '123', 'hello'], ['222', '333', '444', 'bye']]
[['hello'], ['123', 'test'], ['test'], ['456', 'test'], ['789']]
或与:
l = ['hello', '123', 'test', 'test', '456', 'test', '789']
输出将变为:
[['999', '123', 'hello'], ['222', '333', '444', 'bye']]
[['hello'], ['123', 'test'], ['test'], ['456', 'test'], ['789']]
如果在输入的末尾有一个附加的bye
。。。第二个列表输出是否也会有额外的bye
或其他内容?因此,当遇到至少包含一个非数字符号的字符串时,是否要拆分?@JonClements-Yes@oren_isp['hello','123','test','test','456','test','789']
会是什么?@不是机器人-不是-真的-是的,但最好是以最具python风格和最快的方式,因为我必须检查大量数据,我不确定它是否正确-对于['dress','9239307','sheer','pants']
我得到的是['dress','9239307','sheer','sheer',['pants']
而不是['dress'],['9239307','sheer','pants']
我只是复制并粘贴了这个输入,然后自己尝试了一下,我得到了[['dress']、['9239307'、['shear']、['pants']]
作为输出。请确保您的输入在测试中是正确的。