python:如何按所有键对列表进行排序?

ros*_*fun 0 python

在这里,我想写一个函数来排序a

我想这样排序a

a = [[1,3,2],[1,2,3],[2,3,2],[2,3,1]]
def sort(a, sort_index):
  if len(set([_[sort_index] for _ in a])) < len(a):
    key_list = [sort_index] + [i for i in range(len(a[0]))]
    # sort by multi keys.
    a = sorted(a, key=lambda x: (x[i] for i in range(key_list)))
return a
sort(a,0)
Run Code Online (Sandbox Code Playgroud)

这里,sort_index是第一个重要指标。如果 中的值相同sort_index,则将考虑其他索引。所以,结果是预期的:

a = [[1,2,3],[1,3,2],[2,3,1],[2,3,2]]
Run Code Online (Sandbox Code Playgroud)

che*_*ner 6

假设您不想根据子列表的任意排列进行排序,您可以指定一个包含所需元素和原始子列表的键。

def sort(a, sort_index):
    return sorted(a, key=lambda x: (x[sort_index], x))
Run Code Online (Sandbox Code Playgroud)

如果您确实想对任意排列进行排序,请制作sort_index一个可迭代的索引。

def sort(a, sort_indices=None):
    if sort_indices is None:
        # Duplicate the natural sort order of the sublists
        # Assumes a is not empty and all sublists have the same length.
        sort_indices = list(range(len(a[0]))
    return sorted(a, key=lambda x: tuple(x[i] for i in sort_indices)

sort(a, [0])
sort(a, [2, 1])
# etc.
Run Code Online (Sandbox Code Playgroud)