【发布时间】:2019-01-22 02:10:33
【问题描述】:
我有一个列表,其中包含用连字符分隔的浮点数(正数或负数)。我想把它们分开。
例如:
input: -76.833-106.954, -76.833--108.954
output: -76.833,106.954,-76.833,-108.954
我试过re.split(r"([-+]?\d*\.)-",但它不起作用。我得到一个无效的 int() 文字语句
请告诉我您推荐我使用什么代码。谢谢!
【问题讨论】:
我有一个列表,其中包含用连字符分隔的浮点数(正数或负数)。我想把它们分开。
例如:
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]
【讨论】: