通过元素的连续差异求和对矩阵行进行排序的Python程序
给定一个矩阵,下面的文章描述了如何根据行的连续元素之间的差异之和对矩阵的行进行排序。
Input : test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]],
Output : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]
Explanation : 4 < 8 < 9 < 10 is consecutive difference summation.
Input : test_list = [[1, 5, 3, 6], [7, 2, 4, 5], [6, 9, 3, 2]],
Output : [[7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]
Explanation : 8 < 9 < 10 is consecutive difference summation.
方法 1:使用sort()和abs()
在此,我们使用 sort() 执行就地排序任务,abs() 用于获取连续差异总和的绝对值。
Python3
# get abs summation
def diff_sum(row):
return sum([abs(row[idx + 1] - row[idx]) for idx in range(0, len(row) - 1)])
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# performing inplace sort
test_list.sort(key=diff_sum)
# printing result
print("Sorted Rows : " + str(test_list))
Python3
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
res = sorted(test_list, key=lambda row: sum(
[abs(row[idx + 1] - row[idx]) for idx in range(0, len(row) - 1)]))
# printing result
print("Sorted Rows : " + str(res))
输出:
The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Sorted Rows : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]
方法 2:使用sorted() 、 lambda 、 abs()和sum()
在这里,排序是使用 sorted() 完成的,而 lambda函数用于在 sorted() 中注入条件语句。
蟒蛇3
# initializing list
test_list = [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
# printing original list
print("The original list is : " + str(test_list))
# performing sort
res = sorted(test_list, key=lambda row: sum(
[abs(row[idx + 1] - row[idx]) for idx in range(0, len(row) - 1)]))
# printing result
print("Sorted Rows : " + str(res))
输出:
The original list is : [[1, 5, 3, 6], [4, 3, 2, 1], [7, 2, 4, 5], [6, 9, 3, 2]]
Sorted Rows : [[4, 3, 2, 1], [7, 2, 4, 5], [1, 5, 3, 6], [6, 9, 3, 2]]