Boosted_d16
Boosted_d16

Reputation: 14062

Python: append to list IF item is not a number

I'm very close to having this particular function working but I've hit a wall.

I have a list of floats which I would like to round to the nearest whole number ONLY if the element is greater than 0.50. And if there is an unexpected element (anything which is not a number), I would like to leave it the way it is.

mylist = ['58.20','34.99','0.39','0.89','34.55', '-']

expected outcome

mylist = ['58','35','0.39','1','35', '-']

here is my code so far:

[str(int(round(float(x)))) if float(x) > 0.5 else str(x) for x in mylist]

I'm guessing I need to add an 'elif' statement but Im not sure how the expression would look like?

Thanks all!

Upvotes: 1

Views: 2061

Answers (1)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250931

You can use exception handling here:

def solve(x):
    try:
        num = float(x)
        return str(int(round(num))) if num > 0.50 else x
    except ValueError:
        return x
...     
#Using list comprehension
>>> [solve(x) for x in  lis]
['58', '35', '0.39', '1', '35', '-']
#using map
>>> map(solve, lis)
['58', '35', '0.39', '1', '35', '-']

Upvotes: 1

Related Questions