python

  假如你有这样一组数据 [[41, 89, 24], [41, 63, 30], [41, 81, 96]],你希望能将这组数据这样排序:先按第一列从大到小排序,然后再按第二列从大到小排序,最后再第三列从大到小排序,如何 python 实现?

  我们可以使用 python 的 sort 一行实现:

n = int(input())
s = []
for _ in range(n):
    x = input().split(' ')
    s.append((x[0], x[1], x[2]))
s.sort(key=lambda x: (int(x[0]), int(x[1]), int(x[2])), reverse=True)

print(s)

  上面代码将输出结果:

[('41', '89', '24'), ('41', '81', '96'), ('41', '63', '30')]

  但如果你想第一列从大到小排序,第二列从小到大排序呢?其实只需要这样做:

n = int(input())
s = []
for _ in range(n):
    x = input().split(' ')
    s.append((x[0], x[1], x[2]))
s.sort(key=lambda x: (int(x[0]), -int(x[1]), int(x[2])), reverse=True)

print(s)

  这里第二列所有数都加了负号来使其第二列按从小到大排序。

  输出结果:

[('41', '63', '30'), ('41', '81', '96'), ('41', '89', '24')]

  那如果某一列是字符串呢?可以这样做:

n = int(input())
s = []
for _ in range(n):
    x = input().split(' ')
    s.append((x[0], x[1], x[2], x[3]))
s.sort(key=lambda x: (x[1], x[2], x[3], [-ord(_) for _ in x[0]]), reverse=True)

print(s)

  这里的意思是后三列按从大到小排序,如果无法做比较,则按第一列的字典序从小到大排序。

  我们输入:

3
h 41 89 24
a 41 89 24
k 41 89 24

  则上面代码将输出:

[('a', '41', '89', '24'), ('h', '41', '89', '24'), ('k', '41', '89', '24')]

  参考:

    1.https://stackoverflow.com/questions/15138368/python-sort-list-of-lists-over-multiple-levels-and-with-a-custom-order

    2.https://stackoverflow.com/questions/11476371/sort-by-multiple-keys-using-different-orderings

    3.https://docs.python.org/3/howto/sorting.html

原文地址:https://www.cnblogs.com/darkchii/p/12758022.html