Python 如何使用if语句在for循环中获取真值
我无法为嵌套了Python 如何使用if语句在for循环中获取真值,python,python-2.7,optimization,cvxopt,Python,Python 2.7,Optimization,Cvxopt,我无法为嵌套了for循环的if语句获取正确的值。下面是一个用代码编写的示例 # 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矩阵,其与qp1相乘的值小于h1中的相应值,即d11[I]*qp
for循环的if语句获取正确的值。下面是一个用代码编写的示例
# 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矩阵
,其与qp1相乘的值小于h1中的相应值,即d11[I]*qp。此代码为
for x in range(len(d11)):
if d11[x] * qp1 < h1[x]:
a = d11[x]
else:
a = []
范围内x的(len(d11)):
如果d11[x]*qp1
当我们对d11和qp1进行多重计算时,我们得到的值为[26,35,9,22]
。因此,如果我们与h1进行比较,我们发现第二行即35<40
和第三行即9<100
,条件为真,因此答案是[[6,8,1],[1,1]]
。但是我无法得到答案。请建议我正确的方法。如果您的语句正在检查列表理解创建的列表是否为空
[aa[i]>10 for i in range(len(a))]
(即列表[False,False,False,False]
)
由于它不是空的,if
语句的计算结果为True
取而代之,考虑使用<代码>任何< /代码>:
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
将始终是最后一个索引。您的条件相当于:
if len([aa[i] > 10 for i in range(len(a))]):
你正在检查列表是否为空。而且它是非空的——它由四个False
s组成。列表的理解与你想象的不同。您正在检查列表是否为空,并返回列表的最后一个元素
你想要的是:
aa = [1,4,5,6,101]
c = [elem for elem in aa if elem >10]
如果c不是空的,您就知道10以上的元素已经在列表中了 aa[i]
?什么是i
?但如果条件对介于两者之间的某个值为true,则它只返回最后一个值。是的,它由4个“False”值组成,但我需要返回空列表