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