簡體   English   中英

如何使用if語句在for循環中獲取真值

[英]how to get truth value in for loop with if statement

對於嵌套在for loop的條件if statement我無法獲得正確的值。以下是用代碼編寫的示例,

# 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 = []

當我們乘以d11和qp1時,得到的值為[26,35 , 9 ,22]如果與h1進行比較,我們發現第二行(即35< 40和第三行(即9 < 100的條件為True 。答案是[[6,8,1],[1,1,1]] 。但是我無法得到答案。請建議我正確的方法。

您的if語句正在檢查列表理解是否創建了列表
[aa[i] > 10 for i in range(len(a))] (即列表[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將永遠是最后一個索引。

列表Comprehensions與您認為的評估方式不同。 您正在檢查列表是否不為空,並返回列表的最后一個元素。

您想要的東西像:

aa = [1,4,5,6,101]
c = [elem for elem in aa if elem >10]

如果c不為空,則您知道列表中大於10的元素。

您的條件等同於:

if len([aa[i] > 10 for i in range(len(a))]):

即。 您正在檢查列表是否為非空。 它是非空的-由四個False組成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM