格式化列表的所有元素

Cur*_*arn 14 python list string-formatting

我想打印一个数字列表,但我想在打印之前格式化列表中的每个成员.例如,

theList=[1.343465432, 7.423334343, 6.967997797, 4.5522577]
Run Code Online (Sandbox Code Playgroud)

我希望以上列表作为输入打印以下输出:

[1.34, 7.42, 6.97, 4.55]
Run Code Online (Sandbox Code Playgroud)

对于列表中的任何一个成员,我知道我可以使用它来格式化它

print "%.2f" % member
Run Code Online (Sandbox Code Playgroud)

是否有一个命令/功能可以为整个列表执行此操作?我可以写一个,但想知道是否已经存在.

Mar*_*ers 19

如果您只想打印数字,可以使用简单的循环:

for member in theList:
    print "%.2f" % member
Run Code Online (Sandbox Code Playgroud)

如果要稍后存储结果,可以使用列表推导:

formattedList = ["%.2f" % member for member in theList]
Run Code Online (Sandbox Code Playgroud)

然后,您可以打印此列表以获得问题中的输出:

print formattedList
Run Code Online (Sandbox Code Playgroud)

另请注意,%已弃用.如果您使用的是Python 2.6或更新的更喜欢使用format.


rvc*_*and 7

对于Python 3.5.1,您可以使用:

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

结果是:

'  1.343465   7.423334   6.967998   4.552258 '
Run Code Online (Sandbox Code Playgroud)


rau*_*000 5

使用 "".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']
Run Code Online (Sandbox Code Playgroud)