[英]Python TypeError: argument of type 'int' is not iterable problem
[英]Argument of type 'int' is not iterable in python. please explain
我有一個鄰接列表,我嘗試通過將鍵作為參數傳遞給字典來遍歷字典,然后嘗試找出字典中是否存在某個元素(鄰接列表)。 但是,此代碼顯示錯誤。 誰能告訴我如何解決? 代碼:
count = 0
def BackAndForth(AList,end1,end2):
global count
if(end2 in AList[end1]):
count+=1
for i in AList[end1]:
if(i!=end2):
BackAndForth(AList[i],i,end2)
return count
Alist = {
0 :[2, 3, 6],
1 :[3, 5 ,6] ,
2 :[ 0 ,3 ,4],
3 :[ 0 ,1 ,2, 4],
4 : [2 ,3 ,5],
5 :[ 1 ,4 ,6],
6 :[ 0 ,1 ,5],
}
end1=0
end2=0
print(BackAndForth(Alist,end1,end2))
Output:在此處輸入圖像描述
您的 function 在第一次運行時工作正常,但請注意您如何遞歸地將AList[I]
傳遞給BackAndForth
。 那時你有一個數組,這聽起來很棒,但你的代碼end2 in AList[end1])
中也有這個,它會給你一個 int 而不是你期望的列表,一旦它被遞歸調用。 好吧,你決定只通過 AList。 現在你有一個不同的問題,它會無限遞歸。 所以現在你必須告訴它在找到匹配項時停止。 嘗試以下操作,它應該更像您期望的那樣工作:
count = 0
def BackAndForth(AList,end1,end2):
global count
if(end2 in AList[end1]):
count+=1
return count
for i in AList[end1]:
if(i!=end2):
BackAndForth(AList,i,end2)
return count
Alist = {
0 :[2, 3, 6],
1 :[3, 5 ,6] ,
2 :[ 0 ,3 ,4],
3 :[ 0 ,1 ,2, 4],
4 : [2 ,3 ,5],
5 :[ 1 ,4 ,6],
6 :[ 0 ,1 ,5],
}
end1=0
end2=0
print(BackAndForth(Alist,end1,end2))
謝謝老哥,你的解釋。 正如你所說,function 無限遞歸。 之后,我嘗試通過添加一個訪問過的字典來修復它,該字典具有節點作為鍵,值是 true 或 false,具體取決於其是否已訪問的狀態。 我什至在 if 語句中添加了條件(以檢查是否未訪問節點然后繼續)。 但是,它仍然無限遞歸。關於如何阻止這種情況的任何提示?
count = 0
def BackAndForth(AList,end1,end2):
global count
visited={}
for i in AList.keys():
visited[i] = False
print(AList[end1])
visited[end1] = True
if(end2 in AList[end1]):
count+=1
for i in AList[end1]:
if(i!=end2 and not visited[i]):
visited[i] = True
BackAndForth(AList,i,end2)
return count
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.