gpt4 book ai didi

python - 正则表达式重新匹配小数和整数

转载 作者:太空宇宙 更新时间:2023-11-04 10:52:27 26 4
gpt4 key购买 nike

string = '-p 0 0.6724194 0.4034517 -p 0 0 0.4034517 -p 0 0 0.6724194'

arrays = re.findall(r'-?\d+?.\d+|-?\d', string)

我一直在尝试获取字符串中 -p 之后的值的列表。我一直在使用的表达方式没有用。我试图返回这样的东西:

['0, 0.6724194, 0.4034517', '0, 0, 0.4034517', '0, 0, 0.6724194']

显然我稍后会将其转换为 float ,但感谢您的帮助!

我正在寻找正则表达式修复程序,不过还是感谢您提供的其他选项!

最佳答案

试试这个:

>>> st = '-p 0 0.6724194 0.4034517 -p 0 0 0.4034517 -p 0 0 0.6724194'
>>> [f.strip() for f in st.split('-p') if f]
['0 0.6724194 0.4034517', '0 0 0.4034517', '0 0 0.6724194']

或者:

>>> [', '.join(f.strip().split()) for f in st.split('-p') if f]
['0, 0.6724194, 0.4034517', '0, 0, 0.4034517', '0, 0, 0.6724194']

或者,您可能只想得到一个 float 列表的列表:

>>> [[float(e) for e in f.strip().split()] for f in st.split('-p') if f]
[[0.0, 0.6724194, 0.4034517], [0.0, 0.0, 0.4034517], [0.0, 0.0, 0.6724194]]

或者,也许是那些的字典:

>>> {i:[float(e) for e in f.strip().split()] for i,f in enumerate(st.split('-p')[1:])}
{0: [0.0, 0.6724194, 0.4034517], 1: [0.0, 0.0, 0.4034517], 2: [0.0, 0.0, 0.6724194]}

或者,如果你真的想要一个正则表达式:

>>> re.findall(r'-[a-zA-Z]\s(\d?\.?\d+\s\d?\.?\d+\s\d?\.?\d+)', st)
['0 0.6724194 0.4034517', '0 0 0.4034517', '0 0 0.6724194']

关于python - 正则表达式重新匹配小数和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12829463/

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