繁体   English   中英

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

[英]How to separate negative floating numbers which are hyphen separated using python?

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

例如:

input: -76.833-106.954, -76.833--108.954
output: -76.833,106.954,-76.833,-108.954

我已经尝试过re.split(r"([-+]?\\d*\\.)-" ,但是它不起作用。我得到了int()无效的文字语句

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

完成@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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM