[英]Python: list comprehension with boolean as return value
B
is a quadratic matrix of size k
. B
是大小为k
的二次矩阵。
I tried the following code 我尝试了以下代码
if [x for x in range(k) if B[x,1] == 1]:
to get: 要得到:
For the first x
in range(k-1)
, for which B[x,1] == 1
, stop the for-loop and return true
, such that the if-statement can be executed. 对于range(k-1)
的第一个x
range(k-1)
对于B[x,1] == 1
,停止for循环并返回true
,以便可以执行if语句。 If there is no such x
, then return false
and go on in the following code. 如果没有这样的x
,则返回false
并继续下面的代码。
看起来你想要any()
:
if any(B[x,1] == 1 for x in range(k)):
arshajii's answer is probably right, but if you also want to have the value of the first x
fulfilling your condition you could do: arshajii的答案可能是正确的,但是如果您还想让第一个x
的值满足条件,则可以执行以下操作:
try:
x = next(x for x in range(k) if B[x, 1] == 1)
# Do something with x
except StopIteration:
# Do something else
EDIT: Better yet, thanks @arshajii: 编辑:更好的是,谢谢@arshajii:
x = next(x for x in range(k) if B[x, 1] == 1, None)
if x is not None:
# Do something with x
else:
# Do something else
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.