[英]compare two different size array ( component of A is in B )
我想做的是有兩個不同大小的數組讓
A = [[1,3,1],[2,4,1],[3,3,1]]
B = [[1,3,1],[2,5,1],[2,3,1],[3,3,1],[5,5,1]]
B的行可以在A中也可以不在( [1,3,1], [3,3,1] is in A )
我想從這些數組中做的是比較兩個數組,以構造數組“ C”,該數組由A中B的行組成
C = [[1,3,1], [3,3,1]]
我嘗試過pandas.isin但失敗了。任何想法都將非常有幫助
使用set.intersection
例如:
A = [[1,3,1],[2,4,1],[3,3,1]]
B = [[1,3,1],[2,5,1],[2,3,1],[3,3,1],[5,5,1]]
A = map(tuple, A)
B = map(tuple, B)
print(set(A).intersection(set(B)))
輸出:
{(3, 3, 1), (1, 3, 1)}
您可以從兩個列表中獲取通用元素:
>>> A = [[1,3,1],[2,4,1],[3,3,1]]
>>> B = [[1,3,1],[2,5,1],[2,3,1],[3,3,1],[5,5,1]]
>>> print([data for data in A if data in B])
[[1, 3, 1], [3, 3, 1]]
或使用filter
:
print(list(filter(lambda x: x in A.tolist(), B.tolist())))
輸出:
[[1, 3, 1], [3, 3, 1]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.