Skip to content Skip to sidebar Skip to footer

Using If, Elif, Else In List Comprehensions, Python

I created the following list comprehension in python: [int(a[0].internal_value).lower() if type(a[0].internal_value) in (str,unicode) and a[0].internal_value.isdigit() == True els

Solution 1:

You are (ab)using conditional expressions, and they must be of the form true_expression if test else false_expression. These expressions always produce a value, unlike an if compound statement.

Note that you should not test for == True; boolean expressions are already true or false without that test. Don't use <> either, that operator has been deprecated and has removed from Python 3 altogether. When testing for None, a singleton, you'd use is not None however.

You are testing against type() results; that looks like you want to use isinstance() tests instead.

You are also using int() on values, then calling .lower() on the result. There is no int.lower() method, so those calls will fail with an AttributeError.

The following is closer to working just fine, unless there are more types than int, float, str or unicode:

[int(a[0].internal_value) if isinstance(a[0].internal_value, (float, int)) or a[0].internal_value.isdigit() 
 else str(a[0].internal_value).lower()
 for a in ws.iter_rows() if a[0].internal_value is not None]

However, I'd farm out the conversion to filter function instead:

defconversion(value):
    ifisinstance(value, (float, int)):
        returnint(value)
    returnstr(value).lower()

then use that in a list comprehension:

[conversion(a[0].internal_value) for a in ws.iter_rows() if a[0].internal_value is not None]

Solution 2:

It might be easier if you create an auxilary function to help you. I also removed == True and int().lower(). I don't think there's any benefit to cramming all the logic into the list comprehension, but that's up to you.

defhelper(x):
    iftype(x) in (str,unicode) and x.isdigit():
        returnint(x)
    eliftype(x) in (str,unicode):
        returnstr(x).lower()
    eliftype(x) in (float,int):
        returnint(x)

[helper(a[0].internal_value)
 for a in ws.iter_rows()
 if a[0].internal_value <> None]

Post a Comment for "Using If, Elif, Else In List Comprehensions, Python"