簡體   English   中英

兩個代碼有什么區別?

[英]what is the differences between two codes?

最后幾行有什么區別? 為什么第二個是正確的,而第一個不正確? 相反,這似乎很正常。

# I wanted to write this code like this but it is false.Because of
# line 7 and 8.
def is_authorized(my_list,m_name):
    for num in range(len(my_list)):
        if my_list[num].name==m_name and my_list[num].authorized==True:
            return True
        else:
            return False


# program accepts this one. If indentation of line 16 same as line
# 13.

def is_authorized(my_list,m_name):
    for num in range(len(my_list)):
        if my_list[num].name==m_name and my_list[num].authorized==True:
            return True
    return False

第一個代碼


第一個代碼將只檢查第一項,因為即使if條件為假,它也會返回一個值( TrueFalse )。

while True:
    if (condition):
        return True
    else:
        return False

正如你在上面看到的,循環只會執行一次。

第二個代碼


您將檢查所有數組,並且僅當num in range(len(my_list))每個num in range(len(my_list))的條件為 false 時才返回False

while True:
    if (condition):
        return True
    return False

您的第二個代碼具有與any()內置函數非常相似的應用程序。

任何


上面鏈接的 Python 內置函數any()用法如下:

>>> any([True, False, True])
True
>>> any([False, False])
False
>>> array = [1, 2, 3, 4]
>>> booleans = [element > 2 for element in array]
>>> any(booleans)

在您的情況下,您可以執行類似於 jak123 建議的代碼的操作:

def is_authorized(my_list,m_name):
    return any(
        item.name == m_name and item.authorized
        for item in my_list
   )

如前所述,在第一種情況下,for 循環在第一項之后返回。 考慮簡化您的代碼:

def is_authorized(my_list,m_name):
    return any(
        item.name == m_name and item.authorized
        for item in my_list
   )

暫無
暫無

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

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