python中if的效率,Python中列表推导中的多个If / else

I have this

s = ['son','abc','pro','bro']

b = ['son','bro']

c = ['pro','quo']

The expected output is this. Where items in the output are index(item_in_s) if it is present in list b. Or index(item_in_s)+10 if an item is in c.

[0,12,3]

I tried this:

index_list = [s.index(item) if item in b else s.index(item)+10 if item in c for item in s]

print(index)

But apparently this is a syntax error. So I tried this:

index_list = [s.index(item) if item in b else s.index(item)+10 for item in s if item in c]

print(index)

Output:

[12]

This just changes the whole logic. Although I could do this

fin = [s.index(item) if item in b else s.index(item)+10 if item in c else '' for item in s]

fin = [item for item in fin if item!='']

print(fin)

Desired output obtained:

[0, 12, 3]

But how do I obtain what I want in list comprehension itself or is there something like else continue in list comprehensions?

解决方案

Fundamentally, a list-comprehension forces you to be very inefficient:

>>> [i if item in b else i + 10 if item in c else None for i, item in enumerate(s) if item in b or item in c]

[0, 12, 3]

This has to check the membership item in b and c twice each in the worst-case if you want that output. Instead, just use a for-loop:

>>> index_list = []

>>> for i, item in enumerate(s):

... if item in b:

... index_list.append(i)

... elif item in c:

... index_list.append(i + 10)

...

>>> index_list

[0, 12, 3]

>>>

Simple, readable, straight-forward and Pythonic.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值