Python - 计算矩阵行长度的频率
给定一个矩阵,任务是编写一个Python程序来获取其行长度的计数频率。
Input : test_list = [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Output : {3: 2, 2: 2, 1: 1}
Explanation : 2 lists of length 3 are present, 2 lists of size 2 and 1 of 1 length is present.
Input : test_list = [[6, 3, 1], [8, 9], [10, 12, 7], [4, 11]]
Output : {3: 2, 2: 2}
Explanation : 2 lists of length 3 are present, 2 lists of size 2.
方法#1:使用字典+循环
在这我们检查每一行的长度,如果长度已经出现在记忆字典中,那么结果就会增加,或者如果出现新的大小,则元素被注册为新的。
Python3
# Python3 code to demonstrate working of
# Row lengths counts
# Using dictionary + loop
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
[10, 12, 7], [4, 11]]
# printing original list
print("The original list is : " + str(test_list))
res = dict()
for sub in test_list:
# initializing incase of new length
if len(sub) not in res:
res[len(sub)] = 1
# increment in case of length present
else:
res[len(sub)] += 1
# printing result
print("Row length frequencies : " + str(res))
Python3
# Python3 code to demonstrate working of
# Row lengths counts
# Using Counter() + map() + len()
from collections import Counter
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
[10, 12, 7], [4, 11]]
# printing original list
print("The original list is : " + str(test_list))
# Counter gets the frequencies of counts
# map and len gets lengths of sublist
res = dict(Counter(map(len, test_list)))
# printing result
print("Row length frequencies : " + str(res))
输出:
The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {3: 2, 2: 2, 1: 1}
方法#2:使用Counter() + map() + len()
其中,map() 和 len() 获取矩阵中每个子列表的长度,Counter 用于保持每个长度的频率。
蟒蛇3
# Python3 code to demonstrate working of
# Row lengths counts
# Using Counter() + map() + len()
from collections import Counter
# initializing list
test_list = [[6, 3, 1], [8, 9], [2],
[10, 12, 7], [4, 11]]
# printing original list
print("The original list is : " + str(test_list))
# Counter gets the frequencies of counts
# map and len gets lengths of sublist
res = dict(Counter(map(len, test_list)))
# printing result
print("Row length frequencies : " + str(res))
输出:
The original list is : [[6, 3, 1], [8, 9], [2], [10, 12, 7], [4, 11]]
Row length frequencies : {3: 2, 2: 2, 1: 1}