简体   繁体   English

为可变数量的输入概括打印+格式

[英]Generalize print+format for a variable number of inputs

If I have a 3-tuple of floats, and I want to print them formatted, I can do:如果我有一个 3 元组的浮点数,并且我想将它们格式化打印,我可以这样做:

print('{:.2f} {:.2f} {:.2f}'.format(*my_tuple))

And if I have an n-tuple of floats, I can use a map and achieve the same formatting with:如果我有一个 n 元组的浮点数,我可以使用地图并通过以下方式实现相同的格式:

print(*map(lambda x: '{:.2f}'.format(x), my_tuple))

I was wondering, though, if there is a way of changing the print function itself so that it already does the formatting I want for floats without any extra intervention.但是,我想知道是否有一种方法可以更改print功能本身,以便它已经完成了我想要的浮点数格式,而无需任何额外的干预。 I couldn't find anything about that in the docs.我在文档中找不到任何关于它的信息。

I'd like to have a simple print(*my_tuple) that would work also in cases where not all terms in the tuple are floats.我想要一个简单的print(*my_tuple) ,它也适用于元组中并非所有术语都是浮点数的情况。

I am asking this question because it seems like I should be able to tweak print , so I feel I'm missing something simple here.我问这个问题是因为我似乎应该能够调整print ,所以我觉得我在这里错过了一些简单的东西。

Why not simply define your own?为什么不简单地定义你自己的呢? Like so:像这样:

def my_print(data):
    print(', '.join('{:.2f}'.format(x) if type(x)==float else str(x) for x in data))

my_print((1.23, 51212., 5.151252, 1.25, 125.1545, .5314451, 5.1251, 5,.125 , 'sdgsdgdsg'))
# prints:
# 1.23, 51212.00, 5.15, 1.25, 125.15, 0.53, 5.13, 5, 0.12, sdgsdgdsg

After all you would not want to change or redefine the way print() works and you don't have to..毕竟你不想改变或重新定义print()工作方式,你也不必..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM