我有兩個元組串列A和B,它們存盤資料 ID 對,A如果對(x,y)或(y,x)inB也在 中,我想從中洗掉對A。
我嘗試通過使用如下 for 回圈來做到這一點,
A = [(321, 33), (56, 991), (645, 2), (8876, 556)]
B = [(33, 321), (645, 2)]
for pair in B:
if pair in A:
A.remove(pair)
elif (pair[1], pair[0]) in A:
A.remove((pair[1], pair[0]))
print(A) # [(56, 991), (8876, 556)]
但是當串列中的元素很大時,這段代碼運行得很慢。
所以我想讓這段代碼更快,可能避免使用 for 回圈或完全不同的方式。有人可以幫我解決這個問題嗎?
uj5u.com熱心網友回復:
如果A有唯一的專案,您可以將兩個串列轉換為集合并使用集合差異,但需要注意的是您將反向元組添加到B_set:
set_B = set(B).union([(j,i) for (i,j) in B])
out = list(set(A) - set_B)
輸出:
[(321, 33), (645, 2)]
如果A沒有唯一的專案并且您想保留重復的專案,則可以對第二行使用串列理解:
set_B = set(B).union([(j,i) for (i,j) in B])
out = [tpl for tpl in A if tpl in set_B]
uj5u.com熱心網友回復:
假設您使用集合而不是串列,并且第二個集合包含元素的兩種變體((x, y)和(x, y))……
A = {(321, 33), (56, 991), (645, 2), (8876, 556)}
B = {(33, 321), (645, 2), (321, 33), (2, 645)}
你只需要一個集合減法:
print(A - B)
uj5u.com熱心網友回復:
通過排除公共元素來創建一個新串列,而不是洗掉:
[(x,y) for x,y in A if (x,y) not in B and (y,x) not in B]
輸出:
[(56, 991), (8876, 556)]
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/388969.html
上一篇:如何解決raiseValueError("columnsmusthavematchingelementcounts")ValueError:columnsmusthavematch
下一篇:如何匯入其他Python檔案
