Python – 元组矩阵中的元素频率
有时,在使用Python元组矩阵时,我们可能会遇到需要获取其中每个元素的频率的问题。此类问题可能发生在日常编程和 Web 开发领域等领域。让我们讨论一些可以解决这个问题的方法。
Input : test_list = [[(4, 5), (3, 2)], [(2, 2)]]
Output : {4: 1, 5: 1, 3: 1, 2: 3}
Input : test_list = [[(4, 5), (3, 2)]]
Output : {4: 1, 5: 1, 3: 1, 2: 1}
方法#1:使用嵌套链()+“*”运算符+计数器()
上述功能的组合可以用来解决这个问题。在此,我们使用 Counter() 和嵌套链来执行获取频率的任务以迎合嵌套,并且“*”运算符用于执行每个元素的解包和打包。
Python3
# Python3 code to demonstrate working of
# Elements frequency in Tuple Matrix
# Using nested chain() + "*" operator + Counter()
from itertools import chain
from collections import Counter
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
# printing original list
print("The original list is : " + str(test_list))
# Elements frequency in Tuple Matrix
# Using nested chain() + "*" operator + Counter()
res = dict(Counter(chain(*chain(*test_list))))
# printing result
print("Elements frequency : " + str(res))
Python3
# Python3 code to demonstrate working of
# Elements frequency in Tuple Matrix
# Using chain.from_iterables() + Counter()
from itertools import chain
from collections import Counter
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
# printing original list
print("The original list is : " + str(test_list))
# Elements frequency in Tuple Matrix
# Using chain.from_iterables() + Counter()
res = dict(Counter(chain.from_iterable(chain.from_iterable(test_list))))
# printing result
print("Elements frequency : " + str(res))
输出 :
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}
方法 #2:使用 chain.from_iterables() + Counter()
上述功能的组合可以用来解决这个问题。在此,我们使用 chain.from_iterables() 执行打包、解包和展平的任务。
Python3
# Python3 code to demonstrate working of
# Elements frequency in Tuple Matrix
# Using chain.from_iterables() + Counter()
from itertools import chain
from collections import Counter
# initializing lists
test_list = [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
# printing original list
print("The original list is : " + str(test_list))
# Elements frequency in Tuple Matrix
# Using chain.from_iterables() + Counter()
res = dict(Counter(chain.from_iterable(chain.from_iterable(test_list))))
# printing result
print("Elements frequency : " + str(res))
输出 :
The original list is : [[(4, 5), (3, 2)], [(2, 2)], [(1, 2), (5, 5)]]
Elements frequency : {4: 1, 5: 3, 3: 1, 2: 4, 1: 1}