根据另一个列表中定义的元素位置对嵌套列表进行排序[关闭]

问题描述 投票:-2回答:3

假设我有一个嵌套列表,如:

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)方式来做到这一点?建议欢迎!

python list sorting nested
3个回答
1
投票

使用Lambda表达式

你可以使用sorted()函数和下面的lambda表达式作为key来实现它:

#             v  'i-1' since your `ordering` list is holding
#             v   position instead of `index`
lambda x: [x[i-1] for i in ordering]

此lambda表达式将根据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']]

使用operator.itemgetter

使用operator.itemgetter()更好地做到:

>>> from operator import itemgetter

>>> sorted(my_list, key=itemgetter(*[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']]

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']]

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))
© www.soinside.com 2019 - 2024. All rights reserved.