gpt4 book ai didi

python - 正则表达式:用 "/"分割字符

转载 作者:行者123 更新时间:2023-12-02 08:46:34 27 4
gpt4 key购买 nike

我有这些字符串,例如:['2300LO/LCE','2302KO/KCE']

我想要这样的输出:['2300LO','2300LCE','2302KO','2302KCE']

如何在 Python 中使用正则表达式来做到这一点?

谢谢!

最佳答案

您可以制作一个简单的生成器来生成每个字符串的对。然后,您可以使用 itertools.chain()

将它们展平为单个列表
from itertools import product, chain

def getCombos(s):
nums, code = re.match(r'(\d+)(.*)', s).groups()
for pair in product([nums], code.split("/")):
yield ''.join(pair)

a = ['2300LO/LCE','2302KO/KCE']

list(chain.from_iterable(map(getCombos, a)))
# ['2300LO', '2300LCE', '2302KO', '2302KCE']

这还有一个额外的好处,或者使用像 '2300LO/LCE/XX/CC' 这样的字符串,它会给你 ['2300LO', '2300LCE', '2300XX', '2300CC',...]

关于python - 正则表达式:用 "/"分割字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60699859/

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