%precision 2 on Python

本小妞迷上赌 提交于 2020-06-25 03:56:48

问题


If I have this piece of code:

import csv

%precision 2

with open('blah.csv') as csvfile:
    blah = list(csv.DictReader(csvfile))

What does it means the %precision 2 line?


回答1:


This is an IPython magic. It controls how floats display:

>>> 1.2345
1.2345
>>> %precision 2
'%.2f'
>>> 1.2345
1.23

Documented here.

Note: It suggests your script was intended to be executed within an IPython runtime (such as a notebook). In a regular Python interpreter that will be a syntax error.




回答2:


This is to set a floating point precision for printing. It sets the floating point to 2 decimal points. This doesn't work in all interpreters though, but it does work in Jupyter-Notebook.

NB: Thanks to Chrisz for the point.



来源:https://stackoverflow.com/questions/50375504/precision-2-on-python

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