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

标签 python expression findall

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/

相关文章:

python - 向 3 channel 图像中的每个 channel 添加相同的值?

python - 运行 pyxbgen 时出现问题

c# - 创建表达式以使用 out 参数调用方法

python - 在二叉树中查找指定节点的路径(Python)

c# - 在 C# 中有类似 Python 的 'with' 的东西吗?

PHP - 删除任何字母前的任何数字

javascript - 正则表达式不起作用

json - 改变结果grails findAll或response方法

python - 提取分隔符之间具有特定长度的整数

ios - Ansible regex_findall 多个字符串