Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 格式化浮动列表_Python_List_Format - Fatal编程技术网

Python 格式化浮动列表

Python 格式化浮动列表,python,list,format,Python,List,Format,我必须使用%.02f样式格式化我的浮动 我试过: e =[0.2941, 0.1176, 0.0588, 0.2352, 0.1176, 0.1764] print([float(".02f" % x) for x in e]) 但是失败了,所以我试着: print( list(map( '%.02f'.format , e )) ) 它也失败了,我在网上找到了这个: print( list(map( '%.02f'.__mod__ , e )) ) 它给了我一个字符串列表,因此我成功

我必须使用
%.02f
样式格式化我的浮动

我试过:

e =[0.2941, 0.1176, 0.0588, 0.2352, 0.1176, 0.1764]
print([float(".02f" % x)  for x in e])
但是失败了,所以我试着:

print( list(map( '%.02f'.format  , e )) )
它也失败了,我在网上找到了这个:

print( list(map( '%.02f'.__mod__ , e )) )
它给了我一个字符串列表,因此我成功地使用两个命令格式化:

ee = map( '%.02f'.__mod__ , e )
ee = map( float , ee )
好吧,它终于起作用了,但我会错过一些更容易的,不是吗?可以使用列表压缩语法吗?

您应该使用舍入(x,2)来舍入到所需的级别

e =[0.2941, 0.1176, 0.0588, 0.2352, 0.1176, 0.1764]
print([float("{0}".format(round(x,2)))  for x in e])

希望这对您有所帮助

您的原始代码中缺少了一个
%
,这就是它不起作用的原因。使用
float(%.02f”%x)
代替
float(.02f”%x)

或者,使用:

>>> e =[0.2941, 0.1176, 0.0588, 0.2352, 0.1176, 0.1764]
>>> print([float("%.02f" % x)  for x in e])
#                 ^the % is missing
[0.29, 0.12, 0.06, 0.24, 0.12, 0.18]
>>> print([ round(x,2)  for x in e])
[0.29, 0.12, 0.06, 0.24, 0.12, 0.18]