Python - 按无频率对矩阵进行排序
给定一个矩阵,根据 None 元素频率排序。
Input : test_list = [[None, None, 3, None], [12, 4, 5], [None, 3, 4]]
Output : [[12, 4, 5], [None, 3, 4], [None, None, 3, None]]
Explanation : 0, 1, 3 counts of None respectively.
Input : test_list = [[None, None, 3, None], [None, 3, 4]]
Output : [[12, 4, 5], [None, None, 3, None]]
Explanation : 0, 3 counts of None respectively.
方法#1:使用sort()
在此,我们使用 sort() 执行排序,并使用外部函数在每行中提取 None 元素频率的任务。这将执行就地排序。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by None frequency
# Using sort()
# external sort function
def get_None_freq(row):
# getting length of None characters
return len([ele for ele in row if not ele])
# initializing list
test_list = [[None, None, 4], [None, None, 3, None],
[12, 4, 5], [None, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# sorting using sort()
test_list.sort(key = get_None_freq)
# printing result
print("List after sorting : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by None frequency
# Using sorted() + lambda
# initializing list
test_list = [[None, None, 4], [None, None, 3, None],
[12, 4, 5], [None, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# sorting using sorted()
# lambda function for None frequency logic
res = sorted(test_list, key=lambda row: len([ele for ele in row if not ele]))
# printing result
print("List after sorting : " + str(res))
输出:
The original list is : [[None, None, 4], [None, None, 3, None], [12, 4, 5], [None, 3, 4]]
List after sorting : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]
方法 #2:使用 sorted() + lambda
在这里,不是使用外部函数,而是使用 lambda函数来解决这个问题。 sorted() 用于执行排序任务。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by None frequency
# Using sorted() + lambda
# initializing list
test_list = [[None, None, 4], [None, None, 3, None],
[12, 4, 5], [None, 3, 4]]
# printing original list
print("The original list is : " + str(test_list))
# sorting using sorted()
# lambda function for None frequency logic
res = sorted(test_list, key=lambda row: len([ele for ele in row if not ele]))
# printing result
print("List after sorting : " + str(res))
输出:
The original list is : [[None, None, 4], [None, None, 3, None], [12, 4, 5], [None, 3, 4]]
List after sorting : [[12, 4, 5], [None, 3, 4], [None, None, 4], [None, None, 3, None]]