Python – 唯一元组频率(顺序无关)
给定元组列表,以列表顺序提取唯一元组的频率,而不考虑。
Input : test_list = [(3, 4), (1, 2), (4, 3), (3, 4)]
Output : 2
Explanation : (3, 4), (4, 3), (3, 4) makes 1 and (1, 2) is 2nd unique element.
Input : test_list = [(3, 7), (1, 2), (4, 3), (5, 6)]
Output : 4
Explanation : All are different in any order.
方法 #1:使用tuple() + generator expression + sorted() + len()
上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 执行排序任务,以消除顺序约束。 len() 用于计算大小。
# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using tuple() + list comprehension + sorted() + len()
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
# printing original list
print("The original list is : " + str(test_list))
# Using tuple() + list comprehension + sorted() + len()
# Size computed after conversion to set
res = len(list(set(tuple(sorted(sub)) for sub in test_list)))
# printing result
print("Unique tuples Frequency : " + str(res))
输出 :
The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Unique tuples Frequency : 3
方法 #2:使用map() + sorted() + tuple() + set() + len()
上述功能的组合可以用来解决这个问题。在此,我们使用 map() 执行扩展排序逻辑和元组转换的任务,set() 用于消除重复,len() 用于查找容器的长度。
# Python3 code to demonstrate working of
# Unique Tuple Frequency [ Order Irrespective ]
# Using map() + sorted() + tuple() + set() + len()
# initializing lists
test_list = [(3, 4), (1, 2), (4, 3), (5, 6)]
# printing original list
print("The original list is : " + str(test_list))
# Using map() + sorted() + tuple() + set() + len()
# inner map used to perform sort and outer sort to
# convert again in tuple format
res = len(list(set(map(tuple, map(sorted, test_list)))))
# printing result
print("Unique tuples Frequency : " + str(res))
输出 :
The original list is : [(3, 4), (1, 2), (4, 3), (5, 6)]
Unique tuples Frequency : 3