我有一个文本文件,其中包含一个多个点的数字字符串,如'1.2.3'
。我想将此数字转换为float或int,如'1.2.3'
,以便稍后可以将此数字与其他数字进行比较。我在linux下使用python 3.5。要解释这个问题,请考虑这个简单的例子: -
$ python3.5
Python 3.5.2 (default, Sep 10 2016, 08:21:44)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> _str = '1.2.3'
>>> float(_str)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '1.2.3'
>>> _str = '1.2'
>>> float(_str)
1.2
很明显,python不会将包含多个点的数字视为float。我做了很多搜索,但似乎没有人有类似的问题。
我如何克服这个问题?
答案 0 :(得分:1)
我创建了一个名为WrongFloat的类,因为你要求的不是浮点数
from itertools import izip_longest
class WrongFloat:
def __init__(self, val):
if isinstance(val, WrongFloat):
self.parts = val.parts[:]
elif isinstance(val, str):
self.parts=[int(v) for v in val.split('.')]
elif isinstance(val, float):
self.parts=str(val).split('.')
elif isinstance(val, int):
self.parts=[val]
def __str__(self):
return ".".join([str(v) for v in self.parts])
def __lt__(self, val):
o = WrongFloat(val)
parts = list(izip_longest(self.parts, o.parts, fillvalue=0))
for p in parts:
if p[0] > p[1]:
return False
if parts[-1][0] == parts[-1][1]:
return False
return True
def __le__(self, val):
o = WrongFloat(val)
parts = list(izip_longest(self.parts, o.parts, fillvalue=0))
for p in parts:
if p[0] > p[1]:
return False
return True
def __eq__(self, val):
o = WrongFloat(val)
first, second = tuple(zip(*list(izip_longest(self.parts, o.parts, fillvalue=0))))
return first == second
def __ne__(self, val):
o = WrongFloat(val)
first, second = tuple(zip(*list(izip_longest(self.parts, o.parts, fillvalue=0))))
return first != second
def __gt__(self, val):
o = WrongFloat(val)
parts = list(izip_longest(self.parts, o.parts, fillvalue=0))
for p in parts:
if p[0] < p[1]:
return False
if parts[-1][0] == parts[-1][1]:
return False
return True
def __ge__(self, val):
o = WrongFloat(val)
parts = list(izip_longest(self.parts, o.parts, fillvalue=0))
for p in parts:
if p[0] < p[1]:
return False
return True
init 将从string,float,int或其他WrongFloat创建一个实例
所以这可以用于施工
a = WrongFloat("1.2.3")
print a
b = WrongFloat(1.2)
print b
c = WrongFloat(1)
print c
d = WrongFloat(a)
print d
try:
e = WrongFloat("d.r.f")
except ValueError:
print "ValueError"
添加了方法 gt , ge , le , lt , eq 和 ne 所以你可以比较两个值
print a < "1.2.4"
print a < "1.2.3"
print a < "1.2.2"
print a < "1.2.3.1"
print a < "1.2.3.0"
print a < "1.2.2.9"
print a <= "1.2.4"
print a <= "1.2.3"
print a <= "1.2.2"
print a <= "1.2.3.1"
print a <= "1.2.3.0"
print a <= "1.2.2.9"
print a == "1.2.4"
print a == "1.2.3"
print a == "1.2.2"
print a != "1.2.4"
print a != "1.2.3"
print a != "1.2.2"
print a <= "1.2.2"
print a <= "1.2.3"
print a <= "1.2.4"
print a < "1.2.2"
print a < "1.2.3"
print a < "1.2.4"
您还可以使用添加和 sub 方法进行加法和减法,我不认为乘法和除法对于这个带有多个点的浮点类型是合理的< / p>