سؤال

In python3 is there a nice way to set significant figures - i.e if I have a list:

l = [2.2738257169723513, 2.2725769281387329, 2.3101812601089478]

I can use the nice new print system and do

print(*l,sep="\t")

But I'm unclear as to how to set the sigfig with out doing

m = "%.2f, %.2f, %.2f" % (l[0], l[1], l[2])
print(m)

I was wondering if there was an option to print to just say - print all floats to 2 dp?

I guess I could use a loop but that seems not very Python like

هل كانت مفيدة؟

المحلول

Actually, it is definitely pythonic, and it is the only way to do what you're asking. That said, you can still use a comprehension to make this more concise (in this cause a tuple, but you can use a list or use list(map():

# I've changed the name to float_list because l should not be
# used as a variable name in Python according to the standard
# style recommendations
print(*('{0:.2f}'.format(x) for x in float_list), sep="\t")
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top