Python – 为元组分配频率
给定元组列表,为列表中的每个元组分配频率。
Input : test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (9, ), (2, 7)]
Output : [(6, 5, 8, 2), (2, 7, 2), (9, 1)]
Explanation : (2, 7) occurs 2 times, hence 2 is append in tuple.
Input : test_list = [(2, 7), (2, 7), (6, 5, 8), (9, ), (2, 7)]
Output : [(6, 5, 8, 1), (2, 7, 3), (9, 1)]
Explanation : (2, 7) occurs 3 times, hence 3 is append in tuple.
方法 #1:使用 Counter() + items() + * 运算符 + list comprehension
在此,我们使用 Counter() 提取频率,使用 items() 获取频率数,*运算符用于解包元素,列表推导用于将其分配给元组列表中的所有元素。
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# Using Counter() + items() + * operator + list comprehension
from collections import Counter
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# one-liner to solve problem
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).items()]
# printing results
print("Frequency Tuple list : " + str(res))
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# Using most_common() + Counter() + * operator + list comprehension
from collections import Counter
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# most_common performs sort on arg. list
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).most_common()]
# printing results
print("Frequency Tuple list : " + str(res))
输出
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]
方法 #2:使用 most_common() + Counter() + *运算符+ 列表推导
这和上面的方法类似,只是 most_common() 对列表进行排序操作,不是必须的。
Python3
# Python3 code to demonstrate working of
# Assign Frequency to Tuples
# Using most_common() + Counter() + * operator + list comprehension
from collections import Counter
# initializing list
test_list = [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
# printing original list
print("The original list is : " + str(test_list))
# most_common performs sort on arg. list
# assign Frequency as last element of tuple
res = [(*key, val) for key, val in Counter(test_list).most_common()]
# printing results
print("Frequency Tuple list : " + str(res))
输出
The original list is : [(6, 5, 8), (2, 7), (6, 5, 8), (6, 5, 8), (9, ), (2, 7)]
Frequency Tuple list : [(6, 5, 8, 3), (2, 7, 2), (9, 1)]