[英]How to separate negative floating numbers which are hyphen separated using python?
I have a list containing floating numbers (positive or negative) which are separated by a hyphen. 我有一个包含以连字符分隔的浮点数(正数或负数)的列表。 I would like to split them.
我想把它们分开。
For example: 例如:
input: -76.833-106.954, -76.833--108.954
output: -76.833,106.954,-76.833,-108.954
I've tried re.split(r"([-+]?\\d*\\.)-"
, but it doesn't work. I get an invalid literal statement for int() 我已经尝试过
re.split(r"([-+]?\\d*\\.)-"
,但是它不起作用。我得到了int()无效的文字语句
Please let me know what code would you recommend me to use. 请让我知道您建议我使用什么代码。 Thank you!
谢谢!
Completing @PyHunterMan's answer: 完成@PyHunterMan的答案:
You want only one hyphen to be optional before the number indicating a negative float: 您只希望在表示负浮点数的数字前只加一个连字符:
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]
You will notice this does not catch -92
and besides -92
is part the Real numbers set, is not written in float format. 您会注意到这不会捕获
-92
并且-92
是实数集的一部分,不是以浮点格式编写的。
If you want to catch the -92
which is an integer use: 如果要捕获
-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.