如何使用python分隔连字符分隔的负浮点数?

时间:2019-01-22 02:10:33

标签: python numbers floating

我有一个列表,其中包含用连字符分隔的浮点数(正数或负数)。我想把它们分开。

例如:

re.split(r"([-+]?\d*\.)-"

我已经尝试过{{1}},但是它不起作用。我收到int()的无效文字语句

请让我知道您建议我使用什么代码。谢谢!

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

import re

input_ = '-76.833-106.954, -76.833--108.954'
pattern = r'(-{1,2}\d+\.\d+)'
regex = re.findall(pattern, input_)
result = [float(v[1:]) if i % 2 != 0 else float(v)
          for i, v in enumerate(regex)]
print(result)  # [-76.833, 106.954, -76.833, -108.954]

答案 1 :(得分:0)

完成@PyHunterMan的答案:

您只希望在表示负浮点数的数字前只选择一个连字符:

import re

target = '-76.833-106.954, -76.833--108.954, 83.4, -92, 76.833-106.954, 76.833--108.954'
pattern = r'(-?\d+\.\d+)' # Find all float patterns with an and only one optional hypen at the beggining (others are ignored)
match = re.findall(pattern, target)

numbers = [float(item) for item in match]
print(numbers) 

>>> [-76.833, -106.954, -76.833, -108.954, 83.4, 76.833, -106.954, 76.833, -108.954]

您会注意到这并不能捕获-92,并且-92是实数集的一部分,不是以浮点格式编写的。

如果要捕获-92 这是一个整数,请使用:

import re

input_ = '-76.833-106.954, -76.833--108.954, 83.4, -92, 76.833-106.954, 76.833--108.954'
pattern = r'(-?\d+(\.\d+)?)'
match = re.findall(pattern, input_)

print(match)

result = [float(item[0]) for item in match]
print(result) 

>>> [-76.833, -106.954, -76.833, -108.954, 83.4, -92.0, 76.833, -106.954, 76.833, -108.954]