簡體   English   中英

有人可以向我解釋下面提到的python程序的輸出嗎?

[英]Can someone explain to me the output of the below mentioned python program?

我試圖理解下面提到的代碼,但無法理解for i in b的行

a = [1,2]
b = 1
c = [1,2,3,4]
    
def myIn(a,b):
    for i in b:     #what this line is doing here?
        if i==a:
            return(True)
    return(False)   

myIn(a,b) 

這是一個for 循環 在您的示例中,它遍歷一個可迭代對象,例如列表。

我認為變量的類似命名讓你感到困惑。

myIn 是一個接受 2 個參數 a 和 b 的函數,其中 a 是一個變量(不是列表),而 b 是一個列表。

該函數循環遍歷列表 b 中的每個元素,並檢查 b 中的元素是否等於變量 a,如果是,則返回 True,否則返回 False。

這里,在for i in b:循環for i in b:b是一個不可迭代的整數。 您將遇到類似'int' object is not iterable的錯誤消息。

可迭代對象必須是元素的集合。 它可以是列表、字典、集合等。

暫無
暫無

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

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