如何根据每个子列表中的对象对子列表进行排序

How to sort sublists based on an object within each sublist

我有一个列表列表。每个列表包含一个描述词、一个词或句子,然后是一个排序列表。

eg_list = [['sent', 'this is a sentence', [6, 1, 3]]
           ['word', 'abú', [5, 2, 9.5]]
           ['word', 'because', [5, 2, 11]]
           ['sent', 'this is not just one word', [6, 1, 1]]
           ['word', 'ol', [5, 2, 8]]
           ['word', 'magisteriums', [5, 1, 14]]]

我想根据每个子列表末尾的排序列表中的数字对子列表进行排序。我需要它主要按排序列表中的第一个排序,然后是中间的数字,然后是最后一个,这样排序的结果应该如下所示:

['word', 'magisteriums', [5, 1, 14]]
['word', 'ol', [5, 2, 8]]
['word', 'abú', [5, 2, 9.5]]
['word', 'because', [5, 2, 11]]
['sent', 'this is not just one word', [6, 1, 1]]
['sent', 'this is a sentence', [6, 1, 3]]

在Pythonsorted()函数中可以输入什么样的key来排序?

因为您是从左到右比较排序列表及其元素,这是 python 在列表之间进行比较的普通顺序,所以您需要做的就是提供一个关键函数来提取排序列表本身——这可以用 lambda 来完成,如下所示(尽管 operator.itemgetter(2) 是一个替代方案)。无需明确引用排序列表中的元素。

为了提取排序列表,下面的示例在 lambda 中使用 lst[2](即第 3 个元素),但也可以使用 lst[-1](即最后一个元素)。

from pprint import pprint  # pprint used for output display only

eg_list = [['sent', 'this is a sentence', [6, 1, 3]],
           ['word', 'abú', [5, 2, 9.5]],
           ['word', 'because', [5, 2, 11]],
           ['sent', 'this is not just one word', [6, 1, 1]],
           ['word', 'ol', [5, 2, 8]],
           ['word', 'magisteriums', [5, 1, 14]]]

pprint(sorted(eg_list, key=lambda lst:lst[2]))

这给出:

[['word', 'magisteriums', [5, 1, 14]],
 ['word', 'ol', [5, 2, 8]],
 ['word', 'abú', [5, 2, 9.5]],
 ['word', 'because', [5, 2, 11]],
 ['sent', 'this is not just one word', [6, 1, 1]],
 ['sent', 'this is a sentence', [6, 1, 3]]]

Update——您还询问(在评论中)如果您想在 不同命令。在这种情况下,您需要做的是编写一个关键函数来构建一个新的排序列表或元组,其中的元素按所需顺序排列。虽然这可以压缩到 one-liner 中,但为它编写一个显式函数可能更方便。例如,要按中、左、右的顺序排序,您可以使用:

def get_key(lst):
    o_lst = lst[2]
    # let's return a tuple, although list would also work
    return (o_lst[1], o_lst[0], o_lst[2])  

然后您将使用 key=get_key 排序。

等效的 one-liner 将使用:

key=lambda lst:(lst[2][1], lst[2][0], lst[2][2])

但是 lst[2] 的重复在我看来让这不太可取。

无论哪种情况,您都会得到:

[['word', 'magisteriums', [5, 1, 14]],
 ['sent', 'this is not just one word', [6, 1, 1]],
 ['sent', 'this is a sentence', [6, 1, 3]],
 ['word', 'ol', [5, 2, 8]],
 ['word', 'abú', [5, 2, 9.5]],
 ['word', 'because', [5, 2, 11]]]