Python - 测试行是否具有相似的频率
在本文中,我们有一个给定的矩阵,测试是否所有行都有相似的元素。
Input : test_list = [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Output : True
Explanation : All lists have 2, 3, 4, 6, 7.
Input : test_list = [[6, 4, 2, 7, 3], [7, 5, 6, 4, 2], [2, 4, 7, 3, 6]]
Output : False
Explanation : 2nd list has 5 instead of 3.
方法 #1:使用 Counter() + 列表理解
在这里,我们使用 Counter() 计算元素的频率字典,并与 Matrix 中的每一行进行比较,如果它们检出则返回 True。
Python3
# Python3 code to demonstrate working of
# Test if Rows have Similar frequency
# Using Counter() + list comprehension
from collections import Counter
# initializing list
test_list = [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
# printing original list
print("The original list is : " + str(test_list))
# checking if all rows are similar
res = all(dict(Counter(row)) == dict(Counter(test_list[0])) for row in test_list)
# printing result
print("Are all rows similar : " + str(res))
Python3
# Python3 code to demonstrate working of
# Test if Rows have Similar frequency
# Using list comprehension + sorted() + all()
# initializing list
test_list = [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
# printing original list
print("The original list is : " + str(test_list))
# checking if all rows are similar
# ordering each row to test
res = all(list(sorted(row)) == list(sorted(test_list[0])) for row in test_list)
# printing result
print("Are all rows similar : " + str(res))
The original list is : [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Are all rows similar : True
方法 #2:使用列表推导 + sorted() + all()
在这里,我们使用 sorted() 检查相似元素,通过将所有元素排序为排序格式。
蟒蛇3
# Python3 code to demonstrate working of
# Test if Rows have Similar frequency
# Using list comprehension + sorted() + all()
# initializing list
test_list = [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
# printing original list
print("The original list is : " + str(test_list))
# checking if all rows are similar
# ordering each row to test
res = all(list(sorted(row)) == list(sorted(test_list[0])) for row in test_list)
# printing result
print("Are all rows similar : " + str(res))
The original list is : [[6, 4, 2, 7, 3], [7, 3, 6, 4, 2], [2, 4, 7, 3, 6]]
Are all rows similar : True