Reputation: 2725
Let's cut to the chase:
I want to write an iterative print statement, so that given
names = ["val_loss","accuracy","f2_loss"]
values= [0.2454431134, 0.832532234, 0.982762611]
the script should print so that numbers are round off to 6 decimal places, and the list is dynamically iterated on.
Example:
val_loss: 0.245443, accuracy: 0.832532, f2_loss: 0.982762
The kind of iterator I want is something like:
strr = [names[i],":",values[i] for i in range(len(metrics)]
but of course the above doesn't work because I'm not a python wiz. and cannot always write a non-trivial list iterator.
Thanks for your help.
Upvotes: 1
Views: 80
Reputation: 14644
You could use zip and fancy formatting ;)
strs = []
for (name, value) in zip(names, values):
strs.append("{}:{:.6f}".format(name, value))
print(', '.join(strs))
Or, as a fancy 1-liner...
print(', '.join(("{}:{:.6f}".format(n, v) for (n, v) in zip(names, values))))
Explanation
In Python2, use itertools.izip
instead of zip, in Python3, use zip. Zip allows you to lazily merge N-iterables and create tuples of N-length, so zip([1, 2, 3], [4, 5, 6])
effectively becomes [(1, 4), (2, 5), (3, 6)]
. zip is a great tool for any Python programmer.
As for the formatting piece, you should read the documentation. A quick explanation is f
stands for floating pointer numbers, {}
is a replacement group, and :.6f
means a float with a max of 6 decimals.
Upvotes: 4
Reputation: 166
you could do like this:- strr = [name + ":" + str(value) + "," for name in names for value in values]
Upvotes: -2