gpt4 book ai didi

Python:以最优雅的方式拆分这个长度结构的字符串

转载 作者:行者123 更新时间:2023-11-28 22:08:04 25 4
gpt4 key购买 nike

给定这个字符串:

fsw="M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483

我要转换

fsw[8:] (thus "M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483")

在字典中包含:

{'S16d48':'492x577', 'S10000':'505x544', 'S22a00':'506x524', 'S21300':'487x601', 'S37601':'511x574', 'S34500':'482x483'}

我设法用正则表达式得到以下内容:

>>> import re
>>> re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f]",fsw[8:])
['S16d48', 'S10000', 'S22a00', 'S21300', 'S37601', 'S34500']

>>> re.findall("S[123][0-9a-f]{2}[0-5][0-9a-f].......",fsw[8:])
['S16d48492x577', 'S10000505x544', 'S22a00506x524', 'S21300487x601', 'S37601511x574', 'S34500482x483']

但就字典而言......我没有进一步了解。

Another question: in a Python dictionary it is well the whole key-value pair (say "S16d48":"492x577") that must be unique right ?

提前 - 非常感谢。问候。

最佳答案

看来你可以改变你的表情

(?P<key>S[123][0-9a-f]{2}[0-5][0-9a-f])
(?P<value>\d+x\d+)

然后做一个听写理解

import re
rx = re.compile(r'(?P<key>S[123][0-9a-f]{2}[0-5][0-9a-f])(?P<value>\d+x\d+)')

data = "M525x617M525x617S16d48492x577S10000505x544S22a00506x524S21300487x601S37601511x574S34500482x483"

result = {m["key"]: m["value"] for m in rx.finditer(data)}

这产生

{'S16d48': '492x577', 'S10000': '505x544', 'S22a00': '506x524', 'S21300': '487x601', 'S37601': '511x574', 'S34500': '482x483'}


查看表达式 on regex101.com 的演示和 ideone.com 上的代码.

关于Python:以最优雅的方式拆分这个长度结构的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58938480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com