Python - 按大于其前一个元素的元素数对矩阵进行排序
给定一个矩阵,按下一个元素大于当前元素的出现次数排序。计算每个列表中 i < i + 1 的计数,按每行中每个条件的计数对每行进行排序。
Input : test_list = [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
Output : [[6, 3, 2], [5, 3, 2, 5], [4, 6, 2, 9, 10], [2, 4, 5, 6, 7, 7]]
Explanation : for [4, 6, 2, 9, 10], the count is 3 as 6>=4, 9>=2 and 10>=9, similarly for [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2] counts are 1,4 and 0 respectively. As, 0<1<3<4 so the order of rows is [6, 3, 2], [5, 3, 2, 5], [4, 6, 2, 9, 10], [2, 4, 5, 6, 7, 7]
Input : test_list = [[5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
Output : [[6, 3, 2], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7]]
Explanation : 0 < 1 < 4, is the greater next greater elements count. No next element is greater in 1st list.
方法 #1:使用 sort() + len()
在这里,我们使用sort()执行排序任务,并调用外部函数作为 key 来解决计算下一个元素更大的元素的问题。大小是使用len()计算的。
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Next Greater Frequency
# Using sort() + len()
# getting frequency of next greater
def get_greater_freq(row):
# getting length
return len([row[idx] for idx in range(0, len(row) - 1) if row[idx] < row[idx + 1]])
# initializing list
test_list = [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# inplace sorting
test_list.sort(key=get_greater_freq)
# printing result
print("Sorted rows : " + str(test_list))
Python3
# Python3 code to demonstrate working of
# Sort Matrix by Next Greater Frequency
# Using sorted() + len() + lambda
# initializing list
test_list = [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# performing one-liner sorting
# avoiding external fnc. call
res = sorted(test_list, key=lambda row: len(
[row[idx] for idx in range(0, len(row) - 1) if row[idx] < row[idx + 1]]))
# printing result
print("Sorted rows : " + str(res))
输出:
The original list is : [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
Sorted rows : [[6, 3, 2], [5, 3, 2, 5], [4, 6, 2, 9, 10], [2, 4, 5, 6, 7, 7]]
方法 #2:使用 sorted() + len() + lambda
在这种情况下,我们使用sorted() 执行排序任务,lambda和len()用于创建单行功能以执行排序 o 基于大于其前一个元素的元素数量。
蟒蛇3
# Python3 code to demonstrate working of
# Sort Matrix by Next Greater Frequency
# Using sorted() + len() + lambda
# initializing list
test_list = [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# performing one-liner sorting
# avoiding external fnc. call
res = sorted(test_list, key=lambda row: len(
[row[idx] for idx in range(0, len(row) - 1) if row[idx] < row[idx + 1]]))
# printing result
print("Sorted rows : " + str(res))
输出:
The original list is : [[4, 6, 2, 9, 10], [5, 3, 2, 5], [2, 4, 5, 6, 7, 7], [6, 3, 2]]
Sorted rows : [[6, 3, 2], [5, 3, 2, 5], [4, 6, 2, 9, 10], [2, 4, 5, 6, 7, 7]]