在python中对列表中的元组排序

2024-06-06 16:53:18 发布

您现在位置:Python中文网/ 问答频道 /正文

lst=[('fondamenti', 4, 4), ('googlecode', 1, 1), ('stylesheet', 2, 2), ('javascript', 1, 1), ('inlinemath', 1, 1), ('operazioni', 2, 3), ('permettono', 2, 1), ('istruzioni', 4, 3), ('tantissime', 1, 1), ('parentnode', 1, 1)]

如何在列表中排列这些元组? 它们应按发生次数的总和排序,结果应为:

lst=[(u'fondamenti', 4, 4), (u'istruzioni', 4, 3), (u'operazioni', 2, 3), (u'stylesheet', 2, 2), (u'permettono', 2, 1), (u'googlecode', 1, 1), (u'inlinemath', 1, 1), (u'javascript', 1, 1), (u'parentnode', 1, 1), (u'tantissime', 1, 1)]

Tags: 列表javascript次数元组googlecodelst总和stylesheet
1条回答
网友
1楼 · 发布于 2024-06-06 16:53:18

sorted内置有一个key选项,用于提供排序所依据的函数。您想按索引1和索引2的总和排序。这也需要颠倒顺序。你知道吗

>>> sorted(lst, key=lambda x: x[1] + x[2], reverse=True)
[('fondamenti', 4, 4),
 ('istruzioni', 4, 3),
 ('operazioni', 2, 3),
 ('stylesheet', 2, 2),
 ('permettono', 2, 1),
 ('googlecode', 1, 1),
 ('inlinemath', 1, 1),
 ('javascript', 1, 1),
 ('parentnode', 1, 1),
 ('tantissime', 1, 1)]

以上是“交互式会话”表示法,在这里我向您展示了输出,而不指定变量。在实际代码中,您可以执行以下任一操作:

# Sort and return a new object in the same name.
lst = sorted(lst, key=lambda x: x[1] + x[2], reverse=True)
# Or, sort in-place.
lst.sort(key=lambda x: x[1] + x[2], reverse=True)

执行上述任一操作,而不是同时执行。你知道吗

另外,每个元素都是tuple,而不是set。你知道吗

相关问题 更多 >