可能更容易使用
re.split
,因为分隔符是已知的(2个或多个空格),但中间的模式不是。我相信有一个比我更擅长雷杰克斯的人可以解决这个问题,但是通过分开来解决。
\s{2,}
,您可以大大简化问题。
您可以这样编写命名组的字典:
import re
s = "a b d d c"
x = dict(zip('abc', re.split('\s{2,}', s)))
x
{'a': 'a', 'b': 'b d d', 'c': 'c'}
第一个arg在哪里
zip
是命名组。要将此扩展到更通用的名称,请执行以下操作:
groups = ['group_1', 'another group', 'third_group']
x = dict(zip(groups, re.split('\s{2,}', s)))
{'group_1': 'a', 'another group': 'b d d', 'third_group': 'c'}