Home > Python > Practice Python: The List Comprehension

Practice Python: The List Comprehension


Having a list of floating-point number:

34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7

Using the list comprehension to create a new list of integers, rounded from the positive numbers on the given list above.

SOLUTION:

import math
numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
newlist = []

newlist = [int(math.floor(number)) for number in numbers if number > 0]

print newlist

The result is:

[34, 44, 68, 44, 12]

Cheers,
Pete Houston

Advertisements
Categories: Python Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: