📜  Python – 行与 K 的交集

📅  最后修改于: 2022-05-13 01:55:14.329000             🧑  作者: Mango

Python – 行与 K 的交集

有时在使用Python矩阵时,我们可能会遇到一个问题,即我们需要提取与具有特定元素的其他矩阵匹配的所有行。这种问题可能发生在数据域中,因为矩阵是许多问题的输入数据类型。让我们讨论可以执行此任务的某些方式。

方法 #1:使用 sum() + 生成器表达式
上述功能的组合可以用来解决这个问题。在此,我们使用 sum() 执行计数匹配任务,生成器表达式用于执行比较任务。

Python3
# Python3 code to demonstrate working of
# Rows intersection with K
# Using sum() + generator expression
 
# initializing lists
test_list1 = [[5, 6, 7], [7, 6, 6], [5, 7, 10]]
test_list2 = [[5, 6, 7], [7, 6, 8], [5, 7, 10]]
 
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 5
 
# Rows intersection with K
# Using sum() + generator expression
res = sum(sum(a == b for b in test_list2) for a in test_list1 if K in a)
 
# printing result
print("The matched rows : " + str(res))


Python3
# Python3 code to demonstrate working of
# Rows intersection with K
# Using Counter() + sum() + list comprehension
from collections import Counter
 
# initializing lists
test_list1 = [[5, 6, 7], [7, 6, 6], [5, 7, 10]]
test_list2 = [[5, 6, 7], [7, 6, 8], [5, 7, 10]]
 
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 5
 
# Rows intersection with K
# Using Counter() + sum() + list comprehension
temp = Counter(tuple(b) for b in test_list2)
res = sum(temp[tuple(a)] for a in test_list1 if K in a)
 
# printing result
print("The matched rows : " + str(res))


输出 :
The original list 1 is : [[5, 6, 7], [7, 6, 6], [5, 7, 10]]
The original list 2 is : [[5, 6, 7], [7, 6, 8], [5, 7, 10]]
The matched rows : 2


方法 #2:使用 Counter() + sum() + 列表推导
上述功能的组合可以作为解决此问题的替代方案。在此,我们使用 sum() 执行求和,Counter() 用于映射 list2 中的行以与 list1 进行比较,同时计算频率总和。

Python3

# Python3 code to demonstrate working of
# Rows intersection with K
# Using Counter() + sum() + list comprehension
from collections import Counter
 
# initializing lists
test_list1 = [[5, 6, 7], [7, 6, 6], [5, 7, 10]]
test_list2 = [[5, 6, 7], [7, 6, 8], [5, 7, 10]]
 
# printing original list
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
 
# initializing K
K = 5
 
# Rows intersection with K
# Using Counter() + sum() + list comprehension
temp = Counter(tuple(b) for b in test_list2)
res = sum(temp[tuple(a)] for a in test_list1 if K in a)
 
# printing result
print("The matched rows : " + str(res))
输出 :
The original list 1 is : [[5, 6, 7], [7, 6, 6], [5, 7, 10]]
The original list 2 is : [[5, 6, 7], [7, 6, 8], [5, 7, 10]]
The matched rows : 2