我无法获得if statement
嵌套的条件的正确值。这for loop
是一个用代码编写的示例,
# Input data
d11 = np.matrix([[3,6,1],[6,8,1],[1,1,1],[5,8,9]])
qp1 = np.matrix([[1],[3],[5]])
h1 = np.matrix([[5],[40],[100],[5]])
我需要d11 matrix
与 qp1 相乘的值小于 h1 中的相应值的那一行,即d11[i] * qp < h[i]。代码是,
for x in range(len(d11)):
if d11[x] * qp1 < h1[x]:
a = d11[x]
else:
a = []
当我们multipy D11和QP1我们得到的值[26,35 , 9 ,22]
。因此,如果我们用比较H1,我们发现条件为真为第二排即35< 40
和第三排即9 < 100
。所以答案[[6,8,1],[1,1,1]]
。但我无法得到answer.Please建议我的正确方法..
您的if
语句正在检查列表理解创建的列表[aa[i] > 10 for i in range(len(a))]
(即 list [False, False, False, False]
)是否为空。
由于它不是空的,所以if
语句被评估为True
。
相反,请考虑使用any
:
aa = [1, 4, 5, 6]
if any(num > 10 for num in aa):
c = aa[i],'t' # as (correctly) pointed out in the comments below,
# i is not defined here since we are no longer using an index
# to iterate over the list's elements.
# You'll need to decide what you want to do in case an element
# IS larger than 10.
else:
c = 0
您的代码有另一个错误:当列表理解完成时,i
将始终是最后一个索引。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句