假设我有一个嵌套列表,如:
my_list = [[1, 1, "c1"], [1, 2, "c1"], [5, 1, "c2"], [5, 2, "c2"], [6, 1, "c3"], [6, 2, "c3"], [2, 1, "c4"], [2, 2, "c4"], [3, 1, "c5"], [3, 2, "c5"], [4, 1, "c6"], [4, 2, "c6"]]
我还有另一个列表,根据需要对my_list
列表的每个元素执行哪些排序来保持位置。假设它被定义为:
ordering = [2, 1]
现在我想通过多个参数对列表进行排序。首先,我想按列表ordering
进行排序,它应该在索引[1]的ma_list
中排序项目,之后我想按索引[0]中列表中的项目排序。总结一下,我最终想要的是:
list = [[1, 2, "c1"], [2, 2, "c4"], [3, 2, "c5"], [4, 2, "c6"], [5, 2, "c2"], [6, 2, "c3"], [[1, 1, "c1"], [2, 1, "c4"], [3, 1, "c5"], [4, 1, "c6"], [5, 1, "c2"], [6, 1, "c3"]
有没有(更好的Pythonic)方法呢?建议欢迎!
答案 0 :(得分:1)
使用Lambda表达式
您可以将sorted()
函数与下面的lambda表达式一起用作id age iq
1 85 100
来实现它:
key
此lambda表达式将根据# v 'i-1' since your `ordering` list is holding
# v position instead of `index`
lambda x: [x[i-1] for i in ordering]
列表中的索引返回my_list
列表中每个元素的值列表。根据返回的列表,将执行排序。
示例运行:
ordering
更好
>>> my_list = [[1, 1, "c1"], [1, 2, "c1"], [5, 1, "c2"], [5, 2, "c2"], [6, 1, "c3"], [6, 2, "c3"], [2, 1, "c4"], [2, 2, "c4"], [3, 1, "c5"], [3, 2, "c5"], [4, 1, "c6"], [4, 2, "c6"]]
>>> ordering = [2, 1]
>>> sorted(my_list, key=lambda x: [x[i-1] for i in ordering])
[[1, 1, 'c1'], [2, 1, 'c4'], [3, 1, 'c5'], [4, 1, 'c6'], [5, 1, 'c2'], [6, 1, 'c3'], [1, 2, 'c1'], [2, 2, 'c4'], [3, 2, 'c5'], [4, 2, 'c6'], [5, 2, 'c2'], [6, 2, 'c3']]
答案 1 :(得分:0)
要根据ordering
进行排序,您可以尝试:
l = [[1, 1, "c1"], [1, 2, "c1"], [5, 1, "c2"], [5, 2, "c2"], [6, 1, "c3"], [6, 2, "c3"], [2, 1, "c4"], [2, 2, "c4"], [3, 1, "c5"], [3, 2, "c5"], [4, 1, "c6"], [4, 2, "c6"]]
ordering = [2, 1]
new_l = sorted(l, key=lambda x:[x[ordering[0]-1], x[ordering[1]-1]])
输出:
[[1, 1, 'c1'], [2, 1, 'c4'], [3, 1, 'c5'], [4, 1, 'c6'], [5, 1, 'c2'], [6, 1, 'c3'], [1, 2, 'c1'], [2, 2, 'c4'], [3, 2, 'c5'], [4, 2, 'c6'], [5, 2, 'c2'], [6, 2, 'c3']]
答案 2 :(得分:0)
您可以使用运算符模块中的itemgetter来构造已排序的键。
from operator import itemgetter
l = [[1, 1, "c1"], [1, 2, "c1"], [5, 1, "c2"], [5, 2, "c2"], [6, 1, "c3"], [6, 2, "c3"], [2, 1, "c4"], [2, 2, "c4"], [3, 1, "c5"], [3, 2, "c5"], [4, 1, "c6"], [4, 2, "c6"]]
ordering = [1, 0]
new_l = sorted(l, key=itemgetter(*order))