How would I round these float values in the list below to create a list of float values rounded to the nearest whole number using list comprehension? aList = ['3.32', '1.08', '4.23]
and have the new list be [3.0, 1.0, 4.0]
CodePudding user response:
It is pretty easy just use the built function int().
aList = [3.32, 1.08, 4.23]
newList = []
for num in aList:
newList.append(int(num))
print(newList)
Note: those elements in your list are not float numbers but strings.
CodePudding user response:
I'm assuming aList
is supposed to be ['3.32', '1.08', '4.23']
(missing quote at the end).
You can convert the strings into floats, then round them with 0 digits of precision, like this:
newList = [round(float(n), 0) for n in aList]
result:
[3.0, 1.0, 4.0]
CodePudding user response:
input_list = [3.32, 1.08, 4.23]
output_list = [round(x) for x in input_list]