当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Printing a list with string.format rounding for float members

问题描述:

If I have a list of the format ['ABC',0.1234,'DEF'] and I wanted to print it out doing something like

l = ['ABC',0.1234,'DEF']

print('\t'.join(map(str, l)))

But I would also like to round the float so that the output would be ABC\t0.12\tDEF.

I can do it with something like:

a,b,c = l

print('{}\t{:.2f}\t{}'.format(a,b,c))

But since l is just one member of a much larger list, I would like to be able to do this with a list comprehension or something more pythonic.

网友答案:

As mentioned in the comment, you can simply do this for a big list:

print('{}\t{:.2f}\t{}'.format(*l))

Note that .format() also supports indexing the list. Something like:

print('0[0] 0[1] 0[2]'.format(l))

Edit:

"The data structure here is a list of triplet lists. Is there any straightforward way to do string formatting on a unknown size list?" You can try:

>>> print('\t'.join("{:.2f}".format(x) if isinstance(x, float) else str(x) for k
 in l for x in k))
网友答案:

You could use:

print('\t'.join("{:.2f}".format(x) if isinstance(x, float) else str(x) for x in l))
网友答案:

You could define a function for this:

def float_or_str(x):
    try:
        return '{:.2f}'.format(x)
    except ValueError:
        return '{}'.format(x)

l = ['ABC',0.1234,'DEF']
print('\t'.join(map(float_or_str, l)))

yields

ABC 0.12    DEF
分享给朋友:
您可能感兴趣的文章:
随机阅读: