I have a list of floats. If I simply print
it, it shows up like this:
我有一个浮动列表。如果我简单地打印出来,它会这样显示:
[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
I could use print "%.2f"
, which would require a for
loop to traverse the list, but then it wouldn't work for more complex data structures. I'd like something like (I'm completely making this up)
我可以使用打印“%”。它需要一个for循环来遍历列表,但是对于更复杂的数据结构它就不起作用了。我想要(我完全是编造的)
>>> import print_options
>>> print_options.set_float_precision(2)
>>> print [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
[9.0, 0.05, 0.03, 0.01, 0.06, 0.08]
18 个解决方案
#1
2
It's an old question but I'd add something potentially useful:
这是一个古老的问题,但我要补充一些潜在的有用的东西:
I know you wrote your example in raw Python lists, but if you decide to use numpy
arrays instead (which would be perfectly legit in your example, because you seem to be dealing with arrays of numbers), there is (almost exactly) this command you said you made up:
我知道您在原始Python列表中编写了示例,但是如果您决定使用numpy数组(这在您的示例中是完全合法的,因为您似乎正在处理数字数组),那么(几乎完全正确地)有您说过的这个命令:
import numpy as np
np.set_printoptions(precision=2)
Or even better in your case if you still want to see all decimals of really precise numbers, but get rid of trailing zeros for example, use the formatting string %g
:
或者更好的情况是,如果你还想看到所有的小数,但是去掉后面的0,例如,使用格式化字符串%g:
np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})
For just printing once and not changing global behavior, use np.array2string
with the same arguments as above.
对于只打印一次而不改变全局行为,使用np。与上面相同参数的array2string。
#2
70
As noone has added it, it should be noted that going forward from Python 2.6+ the recommended way to do string formating is with format
, to get ready for Python 3+.
正如noone已经添加了它,应该注意的是,从Python 2.6+开始,进行字符串格式化的推荐方式是使用format,以便为Python 3+做好准备。
print ["{0:0.2f}".format(i) for i in a]
The new string formating syntax is not hard to use, and yet is quite powerfull.
新的字符串格式语法使用起来并不困难,但是功能非常强大。
I though that may be pprint
could have something, but I haven't found anything.
我想可能是pprint有什么东西,但我什么都没找到。
#3
66
A more permanent solution is to subclass float
:
一个更持久的解决方案是子类化float:
>>> class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
>>> x
[1.290192, 3.0002, 22.119199999999999, 3.4110999999999998]
>>> x = map(prettyfloat, x)
>>> x
[1.29, 3.00, 22.12, 3.41]
>>> y = x[2]
>>> y
22.12
The problem with subclassing float
is that it breaks code that's explicitly looking for a variable's type. But so far as I can tell, that's the only problem with it. And a simple x = map(float, x)
undoes the conversion to prettyfloat
.
子类化浮点数的问题在于它破坏了显式查找变量类型的代码。但据我所知,这是唯一的问题。一个简单的x = map(float, x)会取消对prettyfloat的转换。
Tragically, you can't just monkey-patch float.__repr__
, because float
's immutable.
不幸的是,你不能仅仅依靠单片浮动。__repr__,因为浮动是不可变的。
If you don't want to subclass float
, but don't mind defining a function, map(f, x)
is a lot more concise than [f(n) for n in x]
如果你不想子类化float,但也不要介意定义一个函数,map(f, x)比[f(n)在x中的n要简洁得多
#4
37
You can do:
你能做什么:
a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]
#5
19
Note that you can also multiply a string like "%.2f" (example: "%.2f "*10).
注意,您还可以将字符串乘以“%”。2 f”(例子:“%。2 f * 10)。
>>> print "%.2f "*len(yourlist) % tuple(yourlist)
2.00 33.00 4.42 0.31
#6
8
print "[%s]"%", ".join(map(str,yourlist))
This will avoid the rounding errors in the binary representation when printed, without introducing a fixed precision constraint (like formating with "%.2f"
):
这将避免打印时二进制表示中的四舍五入误差,而不会引入固定的精度约束(如用“%.2f”格式化):
[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]
#7
4
I believe that Python 3.1 will print them nicer by default, without any code changing. But that is useless if you use any extensions that haven't been updated to work with Python 3.1
我相信Python 3.1默认情况下会打印得更好,不会改变任何代码。但是,如果您使用任何尚未更新的扩展来使用Python 3.1,那么这是没有用处的
#8
4
List comps are your friend.
名单是你的朋友。
print ", ".join("%.2f" % f for f in list_o_numbers)
Try it:
试一试:
>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01
#9
4
The most easy option should be to use a rounding routine:
最简单的选择应该是使用一个舍入例程:
import numpy as np
x=[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print('standard:')
print(x)
print("\nhuman readable:")
print(np.around(x,decimals=2))
This produces the output:
这个生成的输出:
standard:
[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]
human readable:
[ 9. 0.05 0.03 0.01 0.06 0.08]
#10
3
You could use pandas.
你可以用熊猫。
Here is an example with a list:
这里有一个列表的例子:
In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out:
0 3.45
1 2.12
2 6.23
3 6.34
4 9.34
dtype: float64
If you have a dict d, and you want its keys as rows:
如果你有一个命令d,你想要它的键作为行:
In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}
In: P.DataFrame(index=d.keys(), data=d.values())
Out:
0
1 0.45
2 2.35
3 3.42
4 4.13
And another way of giving dict to a DataFrame:
还有另一种给DataFrame的方法:
P.DataFrame.from_dict(d, orient='index')
#11
2
First, elements inside a collection print their repr. you should learn about __repr__
and __str__
.
首先,集合中的元素打印它们的repr。你应该了解……和……。
This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:
这是打印repr(1.1)和打印1.1之间的区别。让我们加入所有这些字符串而不是表示:
numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)
#12
2
I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:
我只是在尝试使用pprint输出浮点数的列表时遇到了这个问题。嵌套的理解可能是个坏主意,但以下是我所做的:
tups = [
(12.0, 9.75, 23.54),
(12.5, 2.6, 13.85),
(14.77, 3.56, 23.23),
(12.0, 5.5, 23.5)
]
pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups])
I used generator expressions at first, but pprint just repred the generator...
我一开始用的是生成器表达式,但是pprint只对生成器进行了repred…
#13
2
l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
Python 2:
Python 2:
print ', '.join('{:0.2f}'.format(i) for i in l)
Python 3:
Python 3:
print(', '.join('{:0.2f}'.format(i) for i in l))
Output:
输出:
9.00, 0.05, 0.03, 0.01, 0.06, 0.08
#14
1
I had this problem, but none of the solutions here did exactly what I wanted (I want the printed output to be a valid python expression), so how about this:
我遇到了这个问题,但是这里的任何一个解决方案都没有达到我想要的效果(我希望打印出来的输出是一个有效的python表达式),那么这个呢?
prettylist = lambda l : '[%s]' % ', '.join("%.2f" % f for f in l)
Usage:
用法:
>>> ugly = [9.0, 0.052999999999999999, 0.032575399999999997,
0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
>>> prettylist = lambda l : '[%s]' % ', '.join("%.2f" % f for f in l)
>>> print prettylist(ugly)
[9.00, 0.05, 0.03, 0.01, 0.06, 0.08]
(I know .format() is supposed to be the more standard solution, but I find this more readable)
(我知道。format()应该是更标准的解决方案,但我觉得这个更容易读)
#15
0
The code below works nice to me.
下面的代码对我来说很有用。
list = map (lambda x: float('%0.2f' % x), list)
#16
0
To control the number of significant digits, use the format specifier %g.
要控制有效数字的数量,请使用格式说明符%g。
Let's name Emile's solution prettylist2f. Here is the modified one:
我们把埃米尔的溶液命名为prettylist2f。这是修改过的一个:
prettylist2g = lambda l : '[%s]' % ', '.join("%.2g" % x for x in l)
Usage:
用法:
>>> c_e_alpha_eps0 = [299792458., 2.718281828, 0.00729735, 8.8541878e-12]
>>> print(prettylist2f(c_e_alpha_eps0)) # [299792458.00, 2.72, 0.01, 0.00]
>>> print(prettylist2g(c_e_alpha_eps0)) # [3e+08, 2.7, 0.0073, 8.9e-12]
If you want flexibility in the number of significant digits, use f-string formatting instead:
如果您想要在有效数字的数量上具有灵活性,可以使用f-string格式:
prettyflexlist = lambda p, l : '[%s]' % ', '.join(f"{x:.{p}}" for x in l)
print(prettyflexlist(3,c_e_alpha_eps0)) # [3e+08, 2.72, 0.0073, 8.85e-12]
#17
0
As of Python 3.6, you can use f-strings:
在Python 3.6中,可以使用f-string:
list_ = [9.0, 0.052999999999999999,
0.032575399999999997, 0.010892799999999999,
0.055702500000000002, 0.079330300000000006]
print(*[f"{element:.2f}" for element in list_])
#9.00 0.05 0.03 0.01 0.06 0.08
You can use print parameters while keeping code very readable:
您可以在保持代码可读性的同时使用打印参数:
print(*[f"{element:.2f}" for element in list_], sep='|', end='<--')
#9.00|0.05|0.03|0.01|0.06|0.08<--
#18
-1
I agree with SilentGhost's comment, the for loop isn't that bad. You can achieve what you want with:
我同意SilentGhost的说法,for循环没有那么糟糕。你可以通过:
l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
for x in l: print "%0.2f" % (x)
#1
2
It's an old question but I'd add something potentially useful:
这是一个古老的问题,但我要补充一些潜在的有用的东西:
I know you wrote your example in raw Python lists, but if you decide to use numpy
arrays instead (which would be perfectly legit in your example, because you seem to be dealing with arrays of numbers), there is (almost exactly) this command you said you made up:
我知道您在原始Python列表中编写了示例,但是如果您决定使用numpy数组(这在您的示例中是完全合法的,因为您似乎正在处理数字数组),那么(几乎完全正确地)有您说过的这个命令:
import numpy as np
np.set_printoptions(precision=2)
Or even better in your case if you still want to see all decimals of really precise numbers, but get rid of trailing zeros for example, use the formatting string %g
:
或者更好的情况是,如果你还想看到所有的小数,但是去掉后面的0,例如,使用格式化字符串%g:
np.set_printoptions(formatter={"float_kind": lambda x: "%g" % x})
For just printing once and not changing global behavior, use np.array2string
with the same arguments as above.
对于只打印一次而不改变全局行为,使用np。与上面相同参数的array2string。
#2
70
As noone has added it, it should be noted that going forward from Python 2.6+ the recommended way to do string formating is with format
, to get ready for Python 3+.
正如noone已经添加了它,应该注意的是,从Python 2.6+开始,进行字符串格式化的推荐方式是使用format,以便为Python 3+做好准备。
print ["{0:0.2f}".format(i) for i in a]
The new string formating syntax is not hard to use, and yet is quite powerfull.
新的字符串格式语法使用起来并不困难,但是功能非常强大。
I though that may be pprint
could have something, but I haven't found anything.
我想可能是pprint有什么东西,但我什么都没找到。
#3
66
A more permanent solution is to subclass float
:
一个更持久的解决方案是子类化float:
>>> class prettyfloat(float):
def __repr__(self):
return "%0.2f" % self
>>> x
[1.290192, 3.0002, 22.119199999999999, 3.4110999999999998]
>>> x = map(prettyfloat, x)
>>> x
[1.29, 3.00, 22.12, 3.41]
>>> y = x[2]
>>> y
22.12
The problem with subclassing float
is that it breaks code that's explicitly looking for a variable's type. But so far as I can tell, that's the only problem with it. And a simple x = map(float, x)
undoes the conversion to prettyfloat
.
子类化浮点数的问题在于它破坏了显式查找变量类型的代码。但据我所知,这是唯一的问题。一个简单的x = map(float, x)会取消对prettyfloat的转换。
Tragically, you can't just monkey-patch float.__repr__
, because float
's immutable.
不幸的是,你不能仅仅依靠单片浮动。__repr__,因为浮动是不可变的。
If you don't want to subclass float
, but don't mind defining a function, map(f, x)
is a lot more concise than [f(n) for n in x]
如果你不想子类化float,但也不要介意定义一个函数,map(f, x)比[f(n)在x中的n要简洁得多
#4
37
You can do:
你能做什么:
a = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print ["%0.2f" % i for i in a]
#5
19
Note that you can also multiply a string like "%.2f" (example: "%.2f "*10).
注意,您还可以将字符串乘以“%”。2 f”(例子:“%。2 f * 10)。
>>> print "%.2f "*len(yourlist) % tuple(yourlist)
2.00 33.00 4.42 0.31
#6
8
print "[%s]"%", ".join(map(str,yourlist))
This will avoid the rounding errors in the binary representation when printed, without introducing a fixed precision constraint (like formating with "%.2f"
):
这将避免打印时二进制表示中的四舍五入误差,而不会引入固定的精度约束(如用“%.2f”格式化):
[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]
#7
4
I believe that Python 3.1 will print them nicer by default, without any code changing. But that is useless if you use any extensions that haven't been updated to work with Python 3.1
我相信Python 3.1默认情况下会打印得更好,不会改变任何代码。但是,如果您使用任何尚未更新的扩展来使用Python 3.1,那么这是没有用处的
#8
4
List comps are your friend.
名单是你的朋友。
print ", ".join("%.2f" % f for f in list_o_numbers)
Try it:
试一试:
>>> nums = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999]
>>> print ", ".join("%.2f" % f for f in nums)
9.00, 0.05, 0.03, 0.01
#9
4
The most easy option should be to use a rounding routine:
最简单的选择应该是使用一个舍入例程:
import numpy as np
x=[9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
print('standard:')
print(x)
print("\nhuman readable:")
print(np.around(x,decimals=2))
This produces the output:
这个生成的输出:
standard:
[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]
human readable:
[ 9. 0.05 0.03 0.01 0.06 0.08]
#10
3
You could use pandas.
你可以用熊猫。
Here is an example with a list:
这里有一个列表的例子:
In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out:
0 3.45
1 2.12
2 6.23
3 6.34
4 9.34
dtype: float64
If you have a dict d, and you want its keys as rows:
如果你有一个命令d,你想要它的键作为行:
In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}
In: P.DataFrame(index=d.keys(), data=d.values())
Out:
0
1 0.45
2 2.35
3 3.42
4 4.13
And another way of giving dict to a DataFrame:
还有另一种给DataFrame的方法:
P.DataFrame.from_dict(d, orient='index')
#11
2
First, elements inside a collection print their repr. you should learn about __repr__
and __str__
.
首先,集合中的元素打印它们的repr。你应该了解……和……。
This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:
这是打印repr(1.1)和打印1.1之间的区别。让我们加入所有这些字符串而不是表示:
numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)
#12
2
I just ran into this problem while trying to use pprint to output a list of tuples of floats. Nested comprehensions might be a bad idea, but here's what I did:
我只是在尝试使用pprint输出浮点数的列表时遇到了这个问题。嵌套的理解可能是个坏主意,但以下是我所做的:
tups = [
(12.0, 9.75, 23.54),
(12.5, 2.6, 13.85),
(14.77, 3.56, 23.23),
(12.0, 5.5, 23.5)
]
pprint([['{0:0.02f}'.format(num) for num in tup] for tup in tups])
I used generator expressions at first, but pprint just repred the generator...
我一开始用的是生成器表达式,但是pprint只对生成器进行了repred…
#13
2
l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
Python 2:
Python 2:
print ', '.join('{:0.2f}'.format(i) for i in l)
Python 3:
Python 3:
print(', '.join('{:0.2f}'.format(i) for i in l))
Output:
输出:
9.00, 0.05, 0.03, 0.01, 0.06, 0.08
#14
1
I had this problem, but none of the solutions here did exactly what I wanted (I want the printed output to be a valid python expression), so how about this:
我遇到了这个问题,但是这里的任何一个解决方案都没有达到我想要的效果(我希望打印出来的输出是一个有效的python表达式),那么这个呢?
prettylist = lambda l : '[%s]' % ', '.join("%.2f" % f for f in l)
Usage:
用法:
>>> ugly = [9.0, 0.052999999999999999, 0.032575399999999997,
0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
>>> prettylist = lambda l : '[%s]' % ', '.join("%.2f" % f for f in l)
>>> print prettylist(ugly)
[9.00, 0.05, 0.03, 0.01, 0.06, 0.08]
(I know .format() is supposed to be the more standard solution, but I find this more readable)
(我知道。format()应该是更标准的解决方案,但我觉得这个更容易读)
#15
0
The code below works nice to me.
下面的代码对我来说很有用。
list = map (lambda x: float('%0.2f' % x), list)
#16
0
To control the number of significant digits, use the format specifier %g.
要控制有效数字的数量,请使用格式说明符%g。
Let's name Emile's solution prettylist2f. Here is the modified one:
我们把埃米尔的溶液命名为prettylist2f。这是修改过的一个:
prettylist2g = lambda l : '[%s]' % ', '.join("%.2g" % x for x in l)
Usage:
用法:
>>> c_e_alpha_eps0 = [299792458., 2.718281828, 0.00729735, 8.8541878e-12]
>>> print(prettylist2f(c_e_alpha_eps0)) # [299792458.00, 2.72, 0.01, 0.00]
>>> print(prettylist2g(c_e_alpha_eps0)) # [3e+08, 2.7, 0.0073, 8.9e-12]
If you want flexibility in the number of significant digits, use f-string formatting instead:
如果您想要在有效数字的数量上具有灵活性,可以使用f-string格式:
prettyflexlist = lambda p, l : '[%s]' % ', '.join(f"{x:.{p}}" for x in l)
print(prettyflexlist(3,c_e_alpha_eps0)) # [3e+08, 2.72, 0.0073, 8.85e-12]
#17
0
As of Python 3.6, you can use f-strings:
在Python 3.6中,可以使用f-string:
list_ = [9.0, 0.052999999999999999,
0.032575399999999997, 0.010892799999999999,
0.055702500000000002, 0.079330300000000006]
print(*[f"{element:.2f}" for element in list_])
#9.00 0.05 0.03 0.01 0.06 0.08
You can use print parameters while keeping code very readable:
您可以在保持代码可读性的同时使用打印参数:
print(*[f"{element:.2f}" for element in list_], sep='|', end='<--')
#9.00|0.05|0.03|0.01|0.06|0.08<--
#18
-1
I agree with SilentGhost's comment, the for loop isn't that bad. You can achieve what you want with:
我同意SilentGhost的说法,for循环没有那么糟糕。你可以通过:
l = [9.0, 0.052999999999999999, 0.032575399999999997, 0.010892799999999999, 0.055702500000000002, 0.079330300000000006]
for x in l: print "%0.2f" % (x)