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

python:如何按所有键对列表排序?,python,Python,在这里,我想写一个函数来对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, k

在这里,我想写一个函数来对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)

假设不希望基于子列表的任意排列进行排序,则可以指定一个键,该键由所需元素以及原始子列表组成

def sort(a, sort_index):
    return sorted(a, key=lambda x: (x[sort_index], x))
如果您确实想对任意排列进行排序,请将sort_索引设置为一个索引的iterable

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.

你能用sort_index=1发布一个结果的例子吗?是否应按顺序考虑其他索引?这里,应首先考虑排序索引,其他索引的顺序并不重要。如果只是从排序索引开始,您可以使用lambda x:x[sort\u index:],x edit:fixed typox[sort\u 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.