I have been working my way through the tutorials on learnpython.org and up to this point have found everything relatively straightforward.
When I came to the question about list comprehension I have become stuck. I have a grasp of how it works. Below is the question that is asked:
Using a list comprehension, create a new list called “newlist” out of
the list “numbers”, which contains only the positive numbers from the
list, as integers.
And the code supplied:
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = []
print newlist
My answer to this question was as follows:
newlist = [x for x in numbers if x > 0]
This returns the correct numbers from the array, but with each item to about 15 dp. How do I get just the integers and not all the decimal places.
For example that answer that is expected is:
[34, 44, 68, 44, 12]
However I end up with:
[34.600000000000001, 44.899999999999999, 68.299999999999997, 44.600000000000001, 12.699999999999999]
If anyone is able to shed some light as to where I am going wrong then it would be much appreciated.
Cheers,
Jamie
This rounds numbers toward zero. Positive numbers will be rounded down and negative numbers will be rounded up. If you want to round to the nearest integer: