1

I have read a lot of similar questions related to my question, but I have not seen any specifically for this. I have a list of objects, such as

l = ((a, 0.5), (b, 0.75), (c, 0.954367))

I want to be able to print out only the numbers, formatted to 5 decimal places. I was not too sure how to go about this, so I started by trying to slice it and then print it as such

nums = list(z[1:2] for z in l)    # originally had 'tuple' instead of 'list'
print("numbers: {:.5f}".format(nums))

The slicing works, giving me only the numbers, but when I get to the print statement I get an error

TypeError: non-empty format string passed to object.__format__

I originally had the slicing to be done as a tuple, but thought that that may have been causing the error so changed it to a list, which did not help. One answer I read noted that "bytes objects do not have a _ _format__ method of their own, so the default from object is used." and suggested converting it to a string instead - which resulted in the same error.

My question essentially, is there a way to fix this error, or a better way to get the output without slicing/using the method above?

Thank you,

3 Answers 3

1

Use simple list comprehension.

>>> l = (('a', 0.5), ('b', 0.75), ('c', 0.954367))
>>> ["{:.5f}".format(i[1]) for i in l]
[ '0.50000', '0.75000', '0.95437']
Sign up to request clarification or add additional context in comments.

Comments

1

You're trying to use a float presentation type, 'f', with a list object. That's the cause of the failure.

Supply print with a list comprehension of the formatted values which you can unpack and provide as positionals:

print("numbers: ", *["{0[0]:.5f}".format(i) for i in nums])

This now prints out:

numbers:  0.50000 0.75000 0.95437

Comments

-1

try:

nums = list(z[1] for z in l)

z[1:2] essentially gives another list of numbers: [[0.5],[0.75],[0.954367]], which I don't think you require.

2 Comments

This answer does not address the 5 decimal place formatting constraint.
this answer was for first line , second line in question was already taking care of 5 decimal point

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.