Reputation: 35
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,
Upvotes: 1
Views: 4377
Reputation: 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.
Upvotes: -1
Reputation: 160567
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
Upvotes: 1
Reputation: 11134
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']
Upvotes: 1