Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: list comprehension with multiple conditions

Tags:

python

I have:

s=  'Lot Size: 1.52 acres'

I want to return a float number only (1.52)

I tried:

>>> o =[s for s in str.split('') if s.isdigit() if s=='.']
>>>

>>>o
>>>[]

How can I get this working?

like image 734
user1592380 Avatar asked Jun 08 '26 06:06

user1592380


2 Answers

This will assign to o a list of the "words" in msg that can be interpreted as floats:

def isFloat(n):
    try:
        return float(n)
    except:
        return None

o = list(filter(isFloat,msg.split()))
like image 73
Scott Hunter Avatar answered Jun 10 '26 18:06

Scott Hunter


You could try the following, with a singular condition and in keeping with your original format (using python 3.6.8) :)

Multiple condition syntax:

[ x for x in x.do() if 'x' in x OR/AND if x == 1]

Example:

s = 'Lot Size: 1.52 acres'

o = [s for s in s.split(' ') if '.' in s]

print(o[0])

Output:

1.52
like image 41
David S Avatar answered Jun 10 '26 18:06

David S



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!