該函式應檢查兩個單獨的串列中是否有兩個相同的值。如果值相同,則應將位置(=索引)保存在附加串列中。回圈后回傳帶有索引的附加串列。
我知道,很簡單,但我是初學者:)
有人能告訴我為什么我在第二個列印陳述句中的輸出是錯誤的嗎?
#Output of my code:
[0, 0, 2, 3, 4]
#Expected Output:
[0, 2, 3, 5]
我的代碼如下所示,帶有雙回圈:
def same_values(lst1, lst2):
lst3 = []
for index1 in range(0,len(lst1)):
for index2 in range(0,len(lst2)):
if lst1[index1] == lst2[index2]:
lst3.append(index1)
else:
continue
return lst3
print(same_values([5, 1, -10, 3, 3, 1], [5, 10, -10, 3, 5, 1]))
有人可以給我一個提示嗎?
uj5u.com熱心網友回復:
zip在這里enumerate很有用:
def same_values(lst1, lst2):
result = []
for n, (x,y) in enumerate(zip(list1, lst2)):
if x==y:
result.append(n)
return result
您的代碼有效的原因是您分別迭代兩個串列,比較以下兩個片段:
for x in range(3):
for y in range(3):
print(x,y)
上面將列印 9 個值,而您有興趣使用相同的索引遍歷兩個串列:
for x, y in zip(range(3), range(3)):
print(x,y)
這將只列印 3 個值。
uj5u.com熱心網友回復:
- 首先,如果你想從 0 到(List -1 的長度)運行回圈,在范圍內你不需要放 -1,因為它默認在給定的數字之前運行。例如,下面的代碼列印:0 1 2 3 4:
for i in range(5):
print(i)
其次,您的第二個回圈運行直到它在 list2 的所有索引中找到 list1 的第 i 個索引中的所有匹配項。因此,list2 中的任何重復匹配都將強制 list3 被追加兩次。
您可以從下面的代碼中清楚地看到:
def same_values(lst1, lst2):
lst3 = []
for index1 in range(len(lst1)):
for index2 in range(len(lst2)):
if lst1[index1] == lst2[index2]:
lst3.append(index1)
print("List1 index number ",index1," value : ",lst1[index1]," matches List2 index number:",index2)
else:
continue
return lst3
print(same_values([5, 1, -10, 3, 3, 1], [5, 10, -10, 3, 5, 1]))
輸出:
List1 index number 0 value : 5 matches List2 index number: 0
List1 index number 0 value : 5 matches List2 index number: 4
List1 index number 1 value : 1 matches List2 index number: 5
List1 index number 2 value : -10 matches List2 index number: 2
List1 index number 3 value : 3 matches List2 index number: 3
List1 index number 4 value : 3 matches List2 index number: 3
List1 index number 5 value : 1 matches List2 index number: 5
[0, 0, 1, 2, 3, 4, 5]
- 最后,如果您想唯一地存盤索引,那么您應該在找到匹配項后中斷第二個回圈,如下所示:
def same_values(lst1, lst2):
lst3 = []
for index1 in range(len(lst1)):
for index2 in range(len(lst2)):
if lst1[index1] == lst2[index2]:
lst3.append(index1)
print("List1 index number ",index1," value : ",lst1[index1]," matches List2 index number:",index2)
break
else:
continue
return lst3
輸出:
List1 index number 0 value : 5 matches List2 index number: 0
List1 index number 1 value : 1 matches List2 index number: 5
List1 index number 2 value : -10 matches List2 index number: 2
List1 index number 3 value : 3 matches List2 index number: 3
List1 index number 4 value : 3 matches List2 index number: 3
List1 index number 5 value : 1 matches List2 index number: 5
[0, 1, 2, 3, 4, 5]
uj5u.com熱心網友回復:
使用簡單的串列推導而不是回圈(并且您不需要 2 個回圈):
def same_values(lst1, lst2):
return [i for i in range(len(lst1)) if lst1[i] == lst2[i]]
print(same_values([5, 1, -10, 3, 3, 1], [5, 10, -10, 3, 5, 1]))
# [0, 2, 3, 5]
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/489172.html
上一篇:使用Pythonpandas資料框列作為通過另一列的回圈的輸入
下一篇:在反應中填充多維陣列
