Python - 按 K 的频率对行进行排序
给定一个矩阵,任务是编写一个Python程序,根据 K 的频率对行进行排序。
Input : test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], K = 2
Output : [[5, 5, 4, 7, 7, 4], [1, 2], [10, 2, 3, 2, 3], [1, 1, 2, 2, 2]]
Explanation : 0 < 1 < 2 < 3, count of K in Matrix order.
Input : test_list = [[5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]], K = 2
Output : [[5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
Explanation : 0 < 1 < 3, count of K in Matrix order.
方法 #1:使用sort() + count()
在这里,我们使用sort()执行就地排序任务,使用count()完成捕获频率。
Python3
# Python3 code to demonstrate working of
# Sort rows by Frequency of K
# Using sort() + count()
def get_Kfreq(row):
# return Frequency
return row.count(K)
# initializing list
test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# performing inplace sort
test_list.sort(key=get_Kfreq)
# printing result
print("Sorted List : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort rows by Frequency of K
# Using sorted() + lambda + count()
# initializing list
test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# performing inplace sort
res = sorted(test_list, key=lambda row: row.count(K))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
Sorted List : [[5, 5, 4, 7, 7, 4], [1, 2], [10, 2, 3, 2, 3], [1, 1, 2, 2, 2]]
方法 #2:使用sorted() + lambda + count()
在这里,我们使用sorted()和lambda执行排序任务,消除了用于计算的外部函数调用和lambda函数。
蟒蛇3
# Python3 code to demonstrate working of
# Sort rows by Frequency of K
# Using sorted() + lambda + count()
# initializing list
test_list = [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 2
# performing inplace sort
res = sorted(test_list, key=lambda row: row.count(K))
# printing result
print("Sorted List : " + str(res))
输出:
The original list is : [[10, 2, 3, 2, 3], [5, 5, 4, 7, 7, 4], [1, 2], [1, 1, 2, 2, 2]]
Sorted List : [[5, 5, 4, 7, 7, 4], [1, 2], [10, 2, 3, 2, 3], [1, 1, 2, 2, 2]]