📌  相关文章
📜  Python|记录相似的元组出现

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

Python|记录相似的元组出现

有时,在处理数据时,我们可能会遇到需要检查出现相似时间的记录的问题。这在Web开发领域有应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用map() + Counter() + sorted

上述功能的组合可用于执行此任务。在此,我们在将数据提供给Counter()之前,为了计算出现次数,对数据进行排序以使所有无序元组有序,以将相似的元组计数为一个。

# Python3 code to demonstrate working of
# Record Similar tuple occurrences
# Using Counter() + map() + sorted
from collections import Counter
  
# initialize list 
test_list = [(3, 1), (1, 3), (2, 5), (5, 2), (6, 3)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Record Similar tuple occurrences
# Using Counter() + map() + sorted
res = dict(Counter(tuple(ele) for ele in map(sorted, test_list)))
  
# printing result
print("The frequency of like tuples : " + str(res))
输出 :
The original list is : [(3, 1), (1, 3), (2, 5), (5, 2), (6, 3)]
The frequency of like tuples : {(2, 5): 2, (1, 3): 2, (3, 6): 1}

方法#2:使用frozenset() + Counter()

上述功能的组合可用于执行此特定任务。在这种情况下,由sorted and map()执行的任务由frozenset()执行,它在内部对元组进行排序。

# Python3 code to demonstrate working of
# Record Similar tuple occurrences
# Using frozenset() + Counter()
from collections import Counter
  
# initialize list 
test_list = [(3, 1), (1, 3), (2, 5), (5, 2), (6, 3)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Record Similar tuple occurrences
# Using frozenset() + Counter()
res = dict(Counter(tuple(frozenset(ele)) for ele in test_list))
  
# printing result
print("The frequency of like tuples : " + str(res))
输出 :
The original list is : [(3, 1), (1, 3), (2, 5), (5, 2), (6, 3)]
The frequency of like tuples : {(2, 5): 2, (1, 3): 2, (3, 6): 1}