sorted()

一、sorted() 简单用法

sorted() 用于对序列进行排序,但是注意是产生一个新的序列,原来的序列的值不会被改变,比如定义 list = [3, 1, 4, 2, 5] ,执行 sorted(list) 之后返回结果为 [1, 2, 3, 4, 5] ,但是 list 的值仍然是 [3, 1, 4, 2, 5]

二、sorted() 复杂用法

语法:sorted(iterable, cmp=None, key=None, reverse=False)

(1) iterable:可迭代的参数,可以通过for循环去遍历的都叫可迭代
(2) cmp:用于比较的函数,比较什么由key决定,如果不写默认值为None
(3) key:指定根据字典的key还是value来排序,如果要使用这个参数需要用到operator模块,operator.itemgetter(0)表示根据key来排序,operator.itemgetter(1)表示根据value来排序
(4) reverse:如果是reverse = True则倒序排序,如果是reverse
= False则正序排序。默认是False

In [4]: x = {1:‘a‘, 2:‘b‘, 3:‘c‘, 4:‘d‘, 5:10, 9:3, 6:3}        //先定义一个字典,我们用这个字典来练习怎么排序

In [5]: import operator          //插入operator模块

In [6]: y = sorted(x.iteritems(), key=operator.itemgetter(0))        //第一个参数x.iteritems()先迭代然后交给后面的operator.itemgetter(0)来排序,0表示根据key来排序,1表示根据value来排序。至于为什么要迭代,用法跟print与return的区别一样,如果没有迭代,那么返回的只是一个生成器对象。

In [7]: y        //查看排序后的值
Out[7]: [(1, ‘a‘), (2, ‘b‘), (3, ‘c‘), (4, ‘d‘), (5, 10), (6, 3), (9, 3)]

In [10]: y = sorted(x.iteritems(), key=operator.itemgetter(0), reverse=True)        //如果加上reverse=True表示倒序排序

In [11]: y
Out[11]: [(9, 3), (6, 3), (5, 10), (4, ‘d‘), (3, ‘c‘), (2, ‘b‘), (1, ‘a‘)]

练习题:找出占用空间大的文件或目录

思路:先对目录做遍历然后组成一个字典,把文件名作为key,把文件大小作为value,然后用sorted倒序排序

#!/usr/bin/env python

import sys
import os
import operator

def get_dic(topdir):                            //先对目录做遍历然后组成一个字典,把文件名作为key,把文件大小作为value
    dic = {}
    a = os.walk(topdir)
    for p, d, f in a:
        for i in f:
            fn = os.path.join(p, i)
            f_size = os.path.getsize(fn)
            dic[fn] = f_size
    return dic

if __name__ == ‘__main__‘:                    //用sorted()倒序排序然后打印出文件大小最大的前10个
    dic = get_dic(sys.argv[1])
    sorted_dic = sorted(dic.iteritems(), key=operator.itemgetter(1), reverse=True)
    for k, v in sorted_dic[:10]:
        print k, ‘-->‘, v
时间: 2024-08-07 19:34:28

sorted()的相关文章

LeetCode OJ 4. Median of Two Sorted Arrays

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). Example 1: nums1 = [1, 3] nums2 = [2] The median is 2.0 Example 2: nums1 = [1,

leetcode修炼之路——83. Remove Duplicates from Sorted List

哈哈,我又来了.昨天发现题目太简单就没有放上来,今天来了一道有序链表的题.题目如下: Given a sorted linked list, delete all duplicates such that each element appear only once. For example, Given 1->1->2, return 1->2. Given 1->1->2->3->3, return 1->2->3. 题目分析:简单来说就是去除有序链

leetcode 109 Convert Sorted List to Binary Search Tree

题目连接 https://leetcode.com/problems/convert-sorted-list-to-binary-search-tree/ Convert Sorted List to Binary Search Tree Description Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST. /** * De

Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Subscribe to see which companies asked this question /** * Definition for singly-linked list. * struct ListN

python笔记-lambda函数、sorted函数、map函数

1.lambda函数:又称匿名函数,示例如下: def f(x): return x**2 print f(4)  #16 g = lambda x:x**2 print g(4)  #16 2.map函数 print map(lambda x:x**2,range(10)) #[0, 1, 4, 9, 16, 25, 36, 49, 64, 81] 3.sorted函数 dict = {9:2,4:3,6:9,'a':'test','e':'fff','*':'$'} print sorted

LeetCode 21 Merge Two Sorted Lists

翻译 合并两个排好序的链表,并返回这个新链表. 新链表应该由这两个链表的头部拼接而成. 原文 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. 代码 /** * Definition for singly-linked list. * struct ListNode

Swift实现的快速排序及sorted方法的对比

Swift语言有着优秀的函数式编程能力,面试的时候面试官都喜欢问我们快速排序,那么用Swift如何实现一个快速排序呢?首先扩展Array类: extension Array { var decompose : (head: T, tail: [T])? { return (count > 0) ? (self[0], Array(self[1..<count])) : nil } } 属性decompose的作用是返回数组中的第一个元素和剩下的元素,注意这个属性是可选型的,当count为0的时

Remove Duplicates from Sorted Array II

Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For example, Given sorted array nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn'

LeetCode --- 88. Merge Sorted Array

题目链接:Merge Sorted Array Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements init

python sort()和sorted()方法

直接上代码: list_a=['a','c','z','E','T','C','b','A','Good','Tack'] list_b=['a','c','z','E','T','C','b','A','Good','Tack'] list_a.sort() print list_a==sorted(list_b)>>>True list_a.sort(), 把list_a原地排序,没有返回值,而是把当前序列变得有序,所以list_a已经完成了排序 sorted(list_b),是内建