python中if elif else流程图,在List Comprehensions中使用if,elif,else,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

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 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:

def conversion(value):

if isinstance(value, (float, int)):

return int(value)

return str(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]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值