如何使用快速排序按列表的列表中的索引排序 [英] How to use the quick sort to sort by index in a list of a list

查看:196
本文介绍了如何使用快速排序按列表的列表中的索引排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用快速排序对索引[1]处的列表进行排序. 例如:

I am trying to use a quick sort to sort through a list of lists at index [1]. For example:

list = [[2, 5, 3],
        [2, 4, 9],
        [0, 9, 1],
        [1, 1, 1],
        [4, 7, 5]]

我希望能够做到这一点,并按索引[1]排序:

I want to be able to do this, sorting by index[1]:

quickSort(list)

output:

list = [[1, 1, 1],
        [2, 4, 9],
        [2, 5, 3],
        [4, 7, 5],
        [0, 9, 1]]

有什么想法吗?

推荐答案

您要在list.sort中使用key自变量:

import operator
mylist = [[2, 5, 3],
          [2, 4, 9],
          [0, 9, 1],
          [1, 1, 1],
          [4, 7, 5]]

mylist.sort(key=operator.itemgetter(1))

输出:

>>> mylist = [[2, 5, 3],
...           [2, 4, 9],
...           [0, 9, 1],
...           [1, 1, 1],
...           [4, 7, 5]]
>>> 
>>> mylist.sort(key=operator.itemgetter(1))
>>> mylist
[[1, 1, 1], [2, 4, 9], [2, 5, 3], [4, 7, 5], [0, 9, 1]]

这篇关于如何使用快速排序按列表的列表中的索引排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆