📜  Python|矩阵中的相对排序顺序

📅  最后修改于: 2022-05-13 01:55:32.166000             🧑  作者: Mango

Python|矩阵中的相对排序顺序

有时,在使用Python Matrix 时,我们可以将数据随机排列,并且我们可能需要以 Matrix 的排序顺序获取元素位置。让我们讨论一下可以执行此任务的某种方式。

方法:使用列表理解 + enumerate() + sort() + lambda
结合上述功能可以解决问题。在这些中,我们首先需要使用enumerate()和列表推导来安排索引值元组创建的元素。然后,我们使用 sort函数使用 lambda函数执行自定义排序。

代码 :

# Python3 code to demonstrate working of
# Relative sorted order in Matrix
# using list comprehension + enumerate() + sort() + lambda
  
# initialize list
test_list = [[1, 3, 1], [4, 6], [7, 8, 10]]
  
# printing original list
print("The original list is : " + str(test_list))
  
# Relative sorted order in Matrix
# using list comprehension + enumerate() + sort() + lambda
res = [(i, j) for i, x in enumerate(test_list) for
       j, _ in enumerate(x)]
res.sort(key = lambda f: test_list[f[0]][f[1]])
  
# printing result
print("Sorted order of Matrix elements : " + str(res))
输出 :
The original list is : [[1, 3, 1], [4, 6], [7, 8, 10]]
Sorted order of Matrix elements : [(0, 0), (0, 2), (0, 1), (1, 0),
                                   (1, 1), (2, 0), (2, 1), (2, 2)]