简体   繁体   中英

Convert block of loop into a list comprehension

I want to convert this snippet

for val in G[k]:
    if val in span[k]:
        result.append((val,col))
    elif val in G[k] and val not in span[k] and S[val][k] != 'col':
        result.append((val,row))

into a list comprehension. But this gives me error:

[(val,col) if val in span[k] else (val,row) if val in G[k] and val not in span[k] and S[val][k] != 'col' for val in G[k]]

So what would be the correct syntax, if there is ie

Change

[(val,col) if val in span[k] else (val,row)
 if val in G[k] and val not in span[k] and S[val][k] != 'col'
 for val in G[k]]

to

[(val,col) if val in span[k] else (val,row)
 for val in G[k]
 if val in G[k] and val not in span[k] and S[val][k] != 'col' ]

Rule of thumb If there is an if before for in comprehension, it must have an else .

You are using conditional expressions without an else part; that's a syntax error.

The correct translation is:

[(val,col) if val in span[k] else (val,row) for val in G[k] if val in span[k] or S[val][k] != 'col']

eg filter out anything that doesn't match your two conditions first, and select between the two branches for values that do result in something added to the output.

I simplified the conditions; there was some redundant testing in the second expression ( val in G[k] is always true for a loop over G[k] and if val in span[k] is not True then the inverse val not in span[k] is certainly True as well and doesn't need to be tested for again.

Personally, I find the explicit for loop more readable, but you can at least simplify it in the same manner:

for val in G[k]:
    if val in span[k]:
        result.append((val,col))
    elif S[val][k] != 'col':
        result.append((val,row))

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