How do I print a list of doubles nicely in python?

纵然是瞬间 提交于 2019-12-11 08:52:29

问题


So far, I've got:

x=[0.0, 1.2135854798749774, 1.0069824713281044, 0.5141246736157659, -0.3396344921640888, -0.33926090064512615, 0.4877599543804152, 0.0]

print ' '.join(["%.2f" % s for s in x])

which produces:

0.00 1.21 1.01 0.51 -0.34 -0.34 0.49 0.00

the problem being that -0.34 is one character longer than 0.51, which produces ragged left edges when printing several lists.

Any better ideas?

I'd like:

0.00 1.21 1.01 0.51 -0.34 -0.34 0.49 0.00
0.00 1.21 1.01 0.51 0.34 0.34 0.49 0.00
0.00 1.21 -1.01 -0.51 -0.34 -0.34 -0.49 0.00

to turn into:

0.00 1.21  1.01  0.51 -0.34 -0.34  0.49 0.00
0.00 1.21  1.01  0.51  0.34  0.34  0.49 0.00
0.00 1.21 -1.01 -0.51 -0.34 -0.34 -0.49 0.00

and it would be even nicer if there was some built in or standard library way of doing this, since print ' '.join(["%.2f" % s for s in x]) is quite a lot to type.


回答1:


Simply adjust the padding for positive and negative numbers accordingly:

''.join(["  %.2f" % s if s >= 0 else " %.2f" % s for s in x]).lstrip()



回答2:


Use rjust or ljust:

x=[0.0, 1.2135854798749774, 1.0069824713281044, 0.5141246736157659, -0.3396344921640888, -0.33926090064512615, 0.4877599543804152, 0.0]

print ' '.join([("%.2f"%s).ljust(5) for s in x])



回答3:


try this: print ' '.join(["%5.2f" % s for s in x]), the number 5 in the string "%5.2f" specifies the maximum field width. It is compatible to the conversion specification in C.




回答4:


have you tried "% .2f" (note: the space)? – J.F. Sebastian



来源:https://stackoverflow.com/questions/22893613/how-do-i-print-a-list-of-doubles-nicely-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!