简体   繁体   中英

Python: For loop over list comprehension

Is there a shorter way to write

for x in [x for x in X if a(x)]:
    <Do something complicated with x>

Unfortunately, the following does not work:

for x in X if a(x):
    <Do something complicated with x>

Of course, I could achieve the desired result by

for x in X:
    if a(x):
        <Do something complicated with x>

but this would introduce an extra level of indentation

  1. [b(x) for x in X if a(x)] is the simplest but will create an unnecessary list.

  2. map(b, (x for x in X if a(x))) will use a generator so no unneeded list will be created.

Not everyone is a fan of the following, but I quite like the map and filter funcs for readability...

list(map(b, filter(a, X))

It will achieve what you want, and I think it's easier to see what's going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM