[英]How to calculate the difference between two lists of lists in Python
我有如下兩個列表:
A = [[1, 2, 3], [1, 2, 4], [4, 5, 6]]
和
B = [[1, 2, 3], [1, 2, 6], [4, 5, 6], [4, 3, 6]]
我希望計算差值,它等於以下內容:
A - B =[[1, 2, 4]]
換句話說,我想將 A 和 B 視為一組列表(所有樣本大小,在本例中為 3)並找出差異(即刪除 B 中的所有列表,這些列表也在 A 中並返回rest。)。
有沒有比為此使用多個 for 循環更快的方法?
簡單的列表理解就可以解決問題:
[a for a in A if a not in B]
output:
[[1, 2, 4]]
如果先將第二個列表轉換為集合,則成員資格測試會漸近地更快; 缺點是您必須將行轉換為元組,以便它們可以在一個集合中。 (首先考慮將行作為元組而不是列表。)
def list_of_lists_subtract(a, b):
b_set = {tuple(row) for row in b}
return [row for row in a if tuple(row) not in b_set]
請注意,“漸近更快”僅意味着對於大輸入應該更快; 對於小輸入,更簡單的版本可能會更快。 如果性能至關重要,那么由您根據實際數據對備選方案進行基准測試。
你可以試試這個。
# (Untested)
A = [[1, 2, 3], [1, 2, 4], [4, 5, 6]]
B = [[1, 2, 3], [1, 2, 6], [4, 5, 6], [4, 3, 6]]
set_A = set([tuple(item) for item in A])
set_B = set([tuple(item) for item in B])
difference_set = set_A - set_B
difference_list = [list(item) for item in sorted(difference_set)]
print(difference_list)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.