简体   繁体   中英

List/Conditional Comprehension in Python

I was wondering how to make the following into a comprehension:

for g in a:
    for f in g[::3]:
        if f == clf.best_params_:
            print g

I tried this:

p = [[print g for g in a] if f==clf.best_params for f in [g[::3] for g in a]]
p

but got an error at for f in

Would love some help! Thanks!

The correct way to translate those loops would be

[print g for g in a for f in g[::3] if f == clf.best_params_]

However, in Python 2 print g is a statement, and that's why you get a SyntaxError. The Python 3 counterpart (ie with print(g) ) would work, but note that a list comprehension here is completely useless. A list comprehension is useful when you have to gather values into a list - here it just hampers the readability.

Regarding the SyntaxError, it's not the primary issue here. Note that you can use

from __future__ import print_function

and then use the print() function in your list comprehension as you would in Python 3.

I think you've confused the construct: it's a list comprehension, not a macro of some sort.

You don't get this sort of side effect; the purpose of a list comprehension is to construct a list.

Rule 1 - Keep the order of the for and if parts the same. The only part that changes order is the last part, print g : that moves to the front.

[print g for g in a for f in g[::3] if f == clf.best_params_]

Rule 2 - List comprehensions should not do anything. Instead of printing g , have g be the value that is accumulated.

[g for g in a for f in g[::3] if f == clf.best_params_]

If your entire goal was simply to print things, stick with the original loops; a list comprehension wouldn't add any value.


If we take another look at your original nested loops, there may be a better way to write them. Is your goal to find all the items g that have clf.best_params_ in one of the matching positions? If so, I recommend replacing the inner loop with a single if any statement.

for g in a:
    if any(f == clf.best_params_ for f in g[::3]):
        print g

To me, this reads better. The logic is clearer. It will only print any one value of g once, instead of multiple times if clf.best_params_ is present more than once.

If that is an improvement, then you could convert that version to a list comprehension like so:

[g for g in a if any(f == clf.best_params_ for f in g[::3])]

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