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
else str(a[0].internal_value).lower() if type(a[0].internal_value) in (str,unicode)
else int(a[0].internal_value) if type(a[0].internal_value) in (float,int)
for a in ws.iter_rows() if a[0].internal_value <> None]
I'm having issues trying to construct the final else, if condition:
else int(a[0].internal_value) if type(a[0].internal_value) in (float,int)
I get an invalid syntax if I use the if conditional in that line.
if type(a[0].internal_value) in (float,int)
If I remove the if statement
else int(a[0].internal_value)
then it seems to run fine. I need to have that if statement in there.
To me the else, if conditions are list comprehensions way of doing the more simple if, else conditions:
if i == x:
do something
elif i == y:
do something
elif i == z:
do something
By rule, you do not always have to have an 'else' to close a series of conditional sentences. It seems to me, that my code wants a final 'else' in the comprehension. Am I correct in stating that and if so, is there a way to construct a final else, if in a python list comprehension instead of a final else?
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 anif
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 forNone
, a singleton, you'd useis not None
however.You are testing against
type()
results; that looks like you want to useisinstance()
tests instead.You are also using
int()
on values, then calling.lower()
on the result. There is noint.lower()
method, so those calls will fail with anAttributeError
.The following is closer to working just fine, unless there are more types than
int
,float
,str
orunicode
:However, I'd farm out the conversion to filter function instead:
then use that in a list comprehension:
It might be easier if you create an auxilary function to help you. I also removed
== True
andint().lower()
. I don't think there's any benefit to cramming all the logic into the list comprehension, but that's up to you.