我正在寻找一种方法将数字转换为字符串格式,删除任何多余的'.0'
输入数据是浮点数和字符串的混合.期望的输出:
0 - >'0'
0.0 - >'0'
0.1 - >'0.1'
1.0 - >'1'
我想出了以下生成器表达式,但我想知道是否有更快的方法:
(str(i).rstrip('.0') if i else '0' for i in lst)
Run Code Online (Sandbox Code Playgroud)
真值检查是为了防止0成为空字符串.
编辑:我现在或多或少可接受的解决方案是:
('%d'%i if i == int(i) else '%s'%i for i in lst)
Run Code Online (Sandbox Code Playgroud)
奇怪的是,在python中没有优雅的方法来处理这个(相当简单的)情况.
小智 68
见PEP 3101:
'g' - General format. This prints the number as a fixed-point
number, unless the number is too large, in which case
it switches to 'e' exponent notation.
老式:
>>> "%g" % float(10)
'10'
Run Code Online (Sandbox Code Playgroud)
新款(推荐):
>>> '{0:g}'.format(float(21))
'21'
Run Code Online (Sandbox Code Playgroud)
dF.*_*dF. 17
rstrip没有做你想做的事情,它会删除你给它的任何字符,而不是后缀:
>>> '30000.0'.rstrip('.0')
'3'
Run Code Online (Sandbox Code Playgroud)
实际上,只会'%g' % i 做你想要的.编辑:正如罗伯特在他的评论中指出的那样,这对大数字不起作用,因为它使用的默认精度为%g,即6位有效数字.
由于str(i)使用12位有效数字,我认为这将有效:
>>> numbers = [ 0.0, 1.0, 0.1, 123456.7 ]
>>> ['%.12g' % n for n in numbers]
['1', '0', '0.1', '123456.7']
Run Code Online (Sandbox Code Playgroud)
小智 9
>>> x = '1.0'
>>> int(float(x))
1
>>> x = 1
>>> int(float(x))
1
Run Code Online (Sandbox Code Playgroud)
(str(i)[-2:] == '.0' and str(i)[:-2] or str(i) for i in ...)
Run Code Online (Sandbox Code Playgroud)
def floatstrip(x):
if x == int(x):
return str(int(x))
else:
return str(x)
Run Code Online (Sandbox Code Playgroud)
但请注意,Python在我的系统0.10000000000000001上表示0.1为不精确浮点数.
要将float具有整数值的a 打印为int:
format = "%d" if f.is_integer() else "%s"
print(format % f)
Run Code Online (Sandbox Code Playgroud)
0.0 -> 0
0.1 -> 0.1
10.0 -> 10
12345678.9 -> 12345678.9
123456789.0 -> 123456789
12345678912345.0 -> 12345678912345
12345678912345.6 -> 1.23456789123e+13
1.000000000001 -> 1.0
Run Code Online (Sandbox Code Playgroud)
那里太丑陋了……
我个人最喜欢的是将float不需要为float(实际上是整数的=)的转换为int,从而删除了现在无用的尾随0
(int(i) if i.is_integer() else i for i in lst)
然后,您可以正常打印它们。
| 归档时间: |
|
| 查看次数: |
50066 次 |
| 最近记录: |