简体   繁体   English

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

[英]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.

相关问题 Python - 从字符串中提取由连字符分隔的数字 - Python - Extract Numbers Separated by Hyphen from String 使用Python正则表达式使用连字符提取电话号码 - Extract phone numbers with hyphen using Python regex 如何存储以分隔的项目<br>使用 Python BeautifulSoup 进入单独的 arrays? - How to store items separated by <br> into separate arrays using Python BeautifulSoup? 用单引号将numpy数组中的数字分开,并用空格分隔 - Separate the numbers in a numpy array which are in single quote separated by spaces 从文本文件 output 中删除连字符,但不删除负数上的连字符 - Deleting a hyphen from a text file output, but not the hyphen on negative numbers 如何使用python3计算计算器问题的负数? - How to calculate negative numbers on calculator problem using python3? 连字符之间用空格分隔的连字符 蟒蛇 - Split hyphen separated words with spaces in between | Python 使用%运算符在python中打印浮点数 - printing floating point numbers in python using % operator 如何获取两个数字之间的值,该数字是字符串并在python中用“-”符号分隔? - How to get values between two numbers which is a string and separated by “-” symbol in python? 使用负数python递归的斐波那契数列 - fibonacci sequence using recursion with negative numbers python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM