📜  Python – 在对偶列表中计算相似对

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

Python – 在对偶列表中计算相似对

有时,在处理数据时,我们可能会遇到问题,即我们收到了对偶元素对,我们打算找到相似元素对及其频率。这种数据通常在数据域中很有用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 Counter() + map() + sorted() + items()
上述功能的组合可用于实现这一特定任务。在此,我们首先使用 Counter 找到频率,然后使用 map() 将其链接到一个元组中。 sorted() 在使用上述方法之前执行排序任务。

Python3
# Python3 code to demonstrate
# Count Similar pair in dual list
# using Counter() + map() + sorted() + items()
from collections import Counter
 
# initializing list
test_list = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 4]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# Count Similar pair in dual list
# using Counter() + map() + sorted() + items()
temp = [sorted(ele) for ele in test_list]
res = [(i, j, k) for (i, j), k in Counter(map(tuple, temp)).items()]
 
# printing result
print ("The dual list similarity counts : " + str(res))


Python3
# Python3 code to demonstrate
# Count Similar pair in dual list
# using sum() + list comprehension + groupby() + sorted()
from itertools import groupby
 
# initializing list
test_list = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 4]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# Count Similar pair in dual list
# using sum() + list comprehension + groupby() + sorted()
res = [(*temp, sum(1 for idx in elements))
      for temp, elements in groupby(test_list, key = lambda j : sorted(j))]
 
# printing result
print ("The dual list similarity counts : " + str(res))


输出 :
The original list is : [[1, 2], [2, 1], [3, 4], [4, 3], [5, 4]]
The dual list similarity counts : [(1, 2, 2), (4, 5, 1), (3, 4, 2)]


方法#2:使用 sum() + list comprehension + groupby() + sorted()
在此方法中,计数任务使用 sum() 执行,获取组任务使用 groupby() 执行。

Python3

# Python3 code to demonstrate
# Count Similar pair in dual list
# using sum() + list comprehension + groupby() + sorted()
from itertools import groupby
 
# initializing list
test_list = [[1, 2], [2, 1], [3, 4], [4, 3], [5, 4]]
 
# printing original list
print ("The original list is : " + str(test_list))
 
# Count Similar pair in dual list
# using sum() + list comprehension + groupby() + sorted()
res = [(*temp, sum(1 for idx in elements))
      for temp, elements in groupby(test_list, key = lambda j : sorted(j))]
 
# printing result
print ("The dual list similarity counts : " + str(res))
输出 :
The original list is : [[1, 2], [2, 1], [3, 4], [4, 3], [5, 4]]
The dual list similarity counts : [(1, 2, 2), (4, 5, 1), (3, 4, 2)]