我寫了這個for循環,但它沒有顯示預期的行爲。爲什麼這個for循環不能遍歷數組中的所有列表
list_of_lists = [[1,2,3],[4,5,6]]
element = 4
for lst in list_of_lists:
if lst.index(element):
found = lst.index(element)
print "success"
print found
break
期望的結果應該是循環給出found = list_of_lists [1] [0]。 但是,它只評估數組中的第一個列表,而不是第二個列表。 如果搜索關鍵字在另一個list_of_lists [0] 我得到的錯誤是。
if lst.index(element):
ValueError: 4 is not in list
謝謝你幫助傢伙!
莫非是'底部break'聲明有什麼關係呢 –
lst.index(4)= 0,因此錯誤 – spicavigo
其實,'lst.index(4)'會產生一個'ValueError'(第一個列表) –