如何获得[-2.3,-2.2,...]的列表? [英] How to get a list of [-2.3,-2.2,...]?

查看:134
本文介绍了如何获得[-2.3,-2.2,...]的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想得到 [ - 2.3,-2.2,...,0.2] 这些数字的列表,在 Python 。然而,尝试:

  [float(i)/ 10为范围内(-23,2)] 

会返回 [ - 2.2999999999999998,-2.2000000000000002,-2.1000000000000001,-2.0,-1.8999999999999999, -1.8,-1.7,-1.6000000000000001,-1.5,-1.3999999999999999,-1.3,-1.2,-1.1000000000000001,-1.0,-0.90000000000000002,-0.80000000000000004,-0.69999999999999996,-0.59999999999999998,-0.5,-0.40000000000000002,-0.29999999999999999,-0.20000000000000001 ,-0.10000000000000001,0.0]



如何解决这个问题?无效:

 >>> round(float(-23)/ float(10),3)
-2.2999999999999998

这是为了最终写入CSV或通过主要方法传递给另一种语言。 解决方案

请不要混淆它的打印与它应该表示为它的值。



打印从来不是一个问题:

 >>>我在范围内(-23,3)]格式(float(i)/ 10)
['-2.3','-2.2','-2.1',['{0:.1f} '-2.0','-1.9','-1.8','-1.7','-1.6','-1.5','-1.4','-1.3','-1.2','-1.1' -0.1,-0.9,-0.8,-0.7,-0.6,-0.5,-0.4,-0.3,-0.2,-0.1 '0.0','0.1','0.2']

但是这些是字符串,表示。当你进行计算时,你需要的是不精确的浮点表示;正如@mitnk指出的那样;和@ 6502解释。

您也可以使用 十进制模块,它提供了更加人性化的浮点数表示形式。


I want to get a list of numbers such as [-2.3,-2.2,...,0.2] in Python. However, the attempt:

[float(i)/10 for i in range(-23,2)] 

will return [-2.2999999999999998, -2.2000000000000002, -2.1000000000000001, -2.0, -1.8999999999999999, -1.8, -1.7, -1.6000000000000001, -1.5, -1.3999999999999999, -1.3, -1.2, -1.1000000000000001, -1.0, -0.90000000000000002, -0.80000000000000004, -0.69999999999999996, -0.59999999999999998, -0.5, -0.40000000000000002, -0.29999999999999999, -0.20000000000000001, -0.10000000000000001, 0.0]

How do I fix this?

Round doesn't work:

>>> round(float(-23)/float(10),3)
-2.2999999999999998

It's for an eventual write to CSV or pass to another language through main method.

解决方案

Please do not confuse how something should look when its printed vs. what it should represent as its value.

Printing is never a problem:

>>> ['{0:.1f}'.format(float(i)/10) for i in range(-23,3)]
['-2.3', '-2.2', '-2.1', '-2.0', '-1.9', '-1.8', '-1.7', '-1.6', '-1.5', '-1.4', '-1.3', '-1.2', '-1.1', '-1.0', '-0.9', '-0.8', '-0.7', '-0.6', '-0.5', '-0.4', '-0.3', '-0.2', '-0.1', '0.0', '0.1', '0.2']

But these are strings, because that's their printed representation. When you are doing calculations, you need the float representation which is not exact; as @mitnk pointed out; and as @6502 explained.

You can also use the decimal module which provides more human-friendly representation of floating point numbers.

这篇关于如何获得[-2.3,-2.2,...]的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆