[英]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
. 经验法则如果有
if
之前for
在理解,它必须有一个else
。
You are using conditional expressions without an else
part; 您正在使用没有
else
部分的条件表达式; 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. 有一个在第二表达一些多余的测试(
val in G[k]
是总是如此为一个循环在G[k]
,并且如果val in span[k]
不是 True
,则逆val not in span[k]
是肯定True
的好,并不需要再次进行测试。
Personally, I find the explicit for
loop more readable, but you can at least simplify it in the same manner: 就个人而言,我发现显式
for
循环更具可读性,但你至少可以用同样的方式简化它:
for val in G[k]:
if val in span[k]:
result.append((val,col))
elif S[val][k] != 'col':
result.append((val,row))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.