且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Python中列表推导中的多个If/else

更新时间:2023-11-29 08:04:34

从根本上说,列表理解会迫使您效率很低:

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.