按字符和整数拆分列表

2024-09-23 14:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

有什么方法可以像这样拆分:

a = 'a3c11d1c3d3'

output = ['a', '3', 'c', '11', 'd', '1', 'c', '3', 'd', '3']

我试过这样做:

list(a)

然而,它给了我这样的结果:

output = ['a', '3', 'c', '1', '1', 'd', '1', 'c', '3', 'd', '3']

Tags: 方法outputlista3c11d1c3d3
2条回答

使用itertools.groupby

from itertools import groupby

a = 'a3c11d1c3d3'
["".join(g) for _, g in groupby(a, key=str.isdigit)]
# ['a', '3', 'c', '11', 'd', '1', 'c', '3', 'd', '3']

您可以使用re.findall并交替匹配字母或数字组:

a = 'a3c11d1c3d3'
output = re.findall(r'[A-Za-z]+|[0-9]+', a)
print(output)

这张照片是:

['a', '3', 'c', '11', 'd', '1', 'c', '3', 'd', '3']

相关问题 更多 >