Python中列表推导中的多个If/else [英] Multiple If/else in list comprehension in Python

查看:481
本文介绍了Python中列表推导中的多个If/else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个

s = ['son','abc','pro','bro']
b = ['son','bro']
c = ['pro','quo']

期望的输出是这个.如果输出在列表b中,则输出中的项目为index(item_in_s).如果项目位于c中,则为index(item_in_s)+10.

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]

我尝试过:

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)

输出:

[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)

获得所需的输出:

[0, 12, 3]

但是我如何在列表理解本身中获得想要的东西,或者列表理解中是否存在类似于else continue的东西?

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]

如果要获得该输出,在最坏的情况下必须将bc 中的成员item分别检查两次.相反,只需使用for循环:

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

简单,易读,简单,Pythonic.

Simple, readable, straight-forward and Pythonic.

这篇关于Python中列表推导中的多个If/else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆