格式化列表中所有元素

26 投票
8 回答
55617 浏览
提问于 2025-04-15 22:18

我想打印一个数字列表,但在打印之前,我想先对列表中的每个数字进行格式化。

theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

比如说,我希望根据上面的列表输入,打印出以下的输出:

[1.34, 7.42, 6.97, 4.55]

对于列表中的任何一个数字,我知道可以通过以下方式来格式化它:

print "%.2f" % member

有没有什么命令或函数可以一次性对整个列表进行格式化?我可以自己写一个,但我在想是否已经有现成的。

8 个回答

10

这里有一个非常简单的解决方案,使用了“”.format()和一个生成器表达式:

>>> theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]

>>> print(['{:.2f}'.format(item) for item in theList])

['1.34', '7.42', '6.97', '4.55']
10

对于Python 3.5.1,你可以使用:

>>> theList = [1.343465432, 7.423334343, 6.967997797, 4.5522577]
>>> strFormat = len(theList) * '{:10f} '
>>> formattedList = strFormat.format(*theList)
>>> print(formattedList)

结果是:

'  1.343465   7.423334   6.967998   4.552258 '
24

如果你只是想打印数字,可以用一个简单的循环来实现:

for member in theList:
    print "%.2f" % member

如果你想把结果存起来以后用,可以使用列表推导式:

formattedList = ["%.2f" % member for member in theList]

然后你可以打印这个列表,得到你想要的输出:

print formattedList

另外要注意的是,%这个写法正在被淘汰。如果你使用的是Python 2.6或更新的版本,建议使用format方法。

撰写回答