Understanding the python list - learnpython.org

I worked through tutorials on learnpython.org and still found it relatively simple.

When I came to the question of understanding the list, I was stuck. I understand how it works. The question below is asked:

Using list comprehension, create a new list called "newlist" from the list of "numbers" that contains only positive numbers from the list, as integers.

And the specified code:

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 element up to about 15 dp. How to get only integers, not all decimals.

For example, the expected response:

[34, 44, 68, 44, 12]

However, in the end I get:

[34.600000000000001, 44.899999999999999, 68.299999999999997, 44.600000000000001, 12.699999999999999]

If someone can shed some light as to where I am going, then that would be very grateful.

Greetings

Jamie

+4
source share
1 answer
 newlist = [int(x) for x in numbers if x > 0] 

These numbers are rounded to zero. Positive numbers will be rounded, and negative numbers will be rounded. If you want to round to the nearest integer:

 newlist = [round(x) for x in numbers if x > 0] 
+4
source

All Articles