#現在我知道有更簡單的方法,但我需要在 #function 中實作,這是我的嘗試。現在它不起作用,但是你能#help me嗎?
def intersection(l1, l2):
l3 = []
for x in range(0, len`length `(l1)):
if x == l2:
l3.append(x)
return l3
print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))
uj5u.com熱心網友回復:
最好/最快的方法是使用set.intersection:
def intersection(l1, l2):
return set(l1).intersection(l2)
uj5u.com熱心網友回復:
您正在嘗試從 0 到迭代整數len(l1)而不是迭代串列項。你應該使用
for x in l1:
代替
for x in range(0, len`length `(l1)):
您在比較專案時也有錯誤。你應該使用:
if x in l2:
代替
if x == l2:
完整代碼示例:
def intersection(l1, l2):
l3 = []
for x in l1:
if x in l2:
l3.append(x)
return l3
print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))
uj5u.com熱心網友回復:
您可以使用 numpy 的 np.intersect1d 方法。
import numpy as np
def intersection(l1, l2):
return np.intersect1d(l1,l2).tolist()
print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))
輸出 :
[1, 4]
uj5u.com熱心網友回復:
您需要同時迭代兩個串列,將每對相加并將其放入新串列中。
def intersection(l1, l2):
result = []
for item1, item2 in zip(l1, l2):
result.append(item1 item2)
return result
print(intersection([2, 3, 4, 7, 1],[0, -1, 4, 5, 1]))
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/398016.html
上一篇:R中的不等組卡方檢驗?
