FROM:https://www.pythoncentral.io/how-to-sort-python-dictionaries-by-key-or-value/

AND https://www.pythoncentral.io/how-to-sort-a-list-tuple-or-object-with-sorted-in-python/

The dict (dictionary) class object in Python is a very versatile and useful container type, able to store a collection of values and retrieve them via keys.

numbers = {'first': 1, 'second': 2, 'third': 3, 'Fourth': 4}

>>> sorted(numbers)

['Fourth', 'first', 'second', 'third']
 
>>> sorted(numbers.values())

[1, 2, 3, 4]
 
>>> sorted(numbers, key=numbers.__getitem__)

# In order of sorted values: [1, 2, 3, 4]
['first', 'second', 'third', 'Fourth']
 
# Uses the first element of each tuple to compare
>>> [value for (key, value) in sorted(numbers.items())]
[4, 1, 2, 3]
# In order of sorted keys: ['Fourth', 'first', 'second', 'third']
 
>>> sorted(numbers, key=numbers.__getitem__, reverse=True)
['Fourth', 'third', 'second', 'first']
>>> [value for (key, value) in sorted(numbers.items(), reverse=True)]
[3, 2, 1, 4]
reverse 标识若为true,顺序为反向排序
 
# Won't change the items to be returned, only while sorting
>>> sorted(numbers, key=str.lower)
['first', 'Fourth', 'second', 'third']
 
>>> month = dict(one='January',
                 two='February',
                 three='March',
                 four='April',
                 five='May')
>>> numbermap = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5}
>>> sorted(month, key=numbermap.__getitem__)
['one', 'two', 'three', 'four', 'five']
同时我们可以对一些字典进行利用一些赋值的数据进行权值排序
 
# Assuming the keys in both dictionaries are EXACTLY the same:
>>> [month[i] for i in sorted(month, key=numbermap.__getitem__)]
['January', 'February', 'March', 'April', 'May']
 
 If we wanted to sort our key/value strings by the number of repeated letters in each string, we could define our own custom method to use in the sorted key argument:
 
def repeats(string):
    # Lower the case in the string
    string = string.lower()
 
    # Get a set of the unique letters
    uniques = set(string)
 
    # Count the max occurrences of each unique letter
    counts = [string.count(letter) for letter in uniques]
 
    return max(counts)
 
# From greatest to least repeats
>>> sorted(month.values(), key=repeats, reverse=True)
['February', 'January', 'March', 'April', 'May']

More advanced sorting functionality

def evens1st(num):
    # Test with modulus (%) two
    if num == 0:
        return -2
    # It's an even number, return the value
    elif num % 2 == 0:
        return num
    # It's odd, return the negated inverse
    else:
        return -1 * (num ** -1)
 
# Max class size first
>>> sorted(trans.values(), key=evens1st, reverse=True)
[30, 24, 33, 7, 0]
Sorting a List(or Tuple) of Custom Python Objects
class Custom(object):
    def __init__(self, name, number):
        self.name = name
        self.number = number
 
    def __repr__(self):
        return '{}: {} {}'.format(self.__class__.__name__,
                                  self.name,
                                  self.number)
def getKey(custom):
    return custom.number
 
>>> sorted(customlist, key=getKey)
[Custom: michael 1, Custom: life 42,
Custom: theodore the great 59, Custom: object 99]
 
Or maybe you feel it's nit-picking,and don't want to type the key keyword everytime,
Redifine our project one more time like this
 
class Custom(object):
    def __init__(self, name, number):
        self.name = name
        self.number = number
 
    def __repr__(self):
        return '{}: {} {}'.format(self.__class__.__name__,
                                  self.name,
                                  self.number)
 
    def __cmp__(self, other):
        if hasattr(other, 'number'):
            return self.number.__cmp__(other.number)
 
>>> sorted(customlist)
[Custom: michael 1, Custom: life 42, Custom: theodore the great 59, Custom: object 99]

Sorting a Heterogeneous List of Custom Python Objects

class AnotherObject(object):
    def __init__(self, tag, age, rate):
        self.tag = tag
        self.age = age
        self.rate = rate
    def __repr__(self):
        return '{}: {} {} {}'.format(self.__class__.__name__,
                                     self.tag,
                                     self.age, self.rate)
    def __cmp__(self, other):
        if hasattr(other, 'age'):
            return self.age.__cmp__(other.age)
customlist = [
    Custom('object', 99),
    Custom('michael', 1),
    Custom('theodore the great', 59),
    Custom('life', 42),
    AnotherObject('bananas', 37, 2.2),
    AnotherObject('pants', 73, 5.6),
    AnotherObject('lemur', 44, 9.2)
]
try it,and ...error:
>>> sorted(customlist)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required
 
Why? Because Custom doesn't have an attribute called age and AnotherObject doesn't have an attribute called number.

Let's redefine those objects again!

class Custom(object):
    def __init__(self,name,number):
        self.name = name
        self.number = number
 
    def __repr__(self):
        return '{}: {} {}'.format(self.__class__.__name__,
                                  self.name,
                                  self.number)
 
    def __cmp__(self, other):
        if hasattr(other, 'getKey'):
            return self.getKey().__cmp__(other.getKey())
 
    def getKey(self):
        return self.number
 
 
class AnotherObject(object):
    def __init__(self, tag, age, rate):
        self.tag = tag
        self.age = age
        self.rate = rate
 
    def __repr__(self):
        return '{}: {} {} {}'.format(self.__class__.__name__,
                                     self.tag,
                                     self.age, self.rate)
 
    def __cmp__(self, other):
        if hasattr(other, 'getKey'):
            return self.getKey().__cmp__(other.getKey())
 
    def getKey(self):
        return self.age

>>> sorted(customlist)
[Custom: michael 1, AnotherObject: bananas 37 2.2,
Custom: life 42, AnotherObject: lemur 44 9.2,
Custom: theodore the great 59, AnotherObject: pants 73 5.6,
Custom: object 99]
And it finally Success
 
You can do that too. If you leave out the __cmp__ functions in each object, and define an outside function like so:
def getKey(customobj):
    return customobj.getKey()\
And then call sorted like so:
>>> sorted(customlist, key=getKey)
[Custom: michael 1, AnotherObject: bananas 37 2.2,
Custom: life 42, AnotherObject: lemur 44 9.2,
Custom: theodore the great 59, AnotherObject: pants 73 5.6,
Custom: object 99]

Sort a list(tuple,dict)的更多相关文章

  1. python学习笔记(二)python基础知识(list,tuple,dict,set)

    1. list\tuple\dict\set d={} l=[] t=() s=set() print(type(l)) print(type(d)) print(type(t)) print(typ ...

  2. Python容器--list, tuple, dict, set

    ## Python 中有四种用于存放数据的序列--list, tuple, dict, set ## list 列表 - 可以存放任意类型数据的有序序列 - 列表可以由零个或多个元素组成,元素之间用逗 ...

  3. day3------基本数据类型int, bool, str,list,tuple,dict

    基本数据类型(int, bool, str,list,tuple,dict) 一.python基本数据类型 1. int  整数. 主要用来进行数学运算 2. str  字符串, 可以保存少量数据并进 ...

  4. list,tuple,dict,set常用方法

    Python中list,tuple,dict,set常用方法 collections模块提供的其它有用扩展类型 from collections import Counter from collect ...

  5. Python中内置数据类型list,tuple,dict,set的区别和用法

    Python中内置数据类型list,tuple,dict,set的区别和用法 Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, ...

  6. Python中list,tuple,dict,set的区别和用法

    Python语言简洁明了,可以用较少的代码实现同样的功能.这其中Python的四个内置数据类型功不可没,他们即是list, tuple, dict, set.这里对他们进行一个简明的总结. List ...

  7. python学习中,list/tuple/dict格式化遇到的问题

    昨天上了python培训的第一课,学习了基础知识.包括类型和赋值,函数type(),dir(),id(),help()的使用,list/tuple/dict的定义以及内置函数的操作,函数的定义,控制语 ...

  8. list,tuple,dict,set的增删改查

    数据结构 list tuple dict set 增 append insert    d['key']=value  add 删 pop pop(0)    d.pop('name') pop re ...

  9. 关于容器类型数据的强转一共:str() list() set() tuple() dict() 都可以转换成对应的数据类型 /Number 数据类型的强转一共: int() bool() flaot() complex() 都可以转换成对应的数据类型

    # ###强制转换成字典类型 # 多级容器数据:该类型是容器数据,并且里面的元素还是容器类型数据 # ###二级容器 # 二级列表 listvar = [1,3,4,5,[6,7,8,9]] res ...

随机推荐

  1. 前后端分离,如何防止api接口被恶意调用或攻击

    无论网站,还是App目前基本都是基于api接口模式的开发,那么api的安全就尤为重要了.目前攻击最常见的就是“短信轰炸机”,由于短信接口验证是App,网站检验用户手机号最真实的途径,使用短信验证码在提 ...

  2. TypeScript 高级类型 接口(interface)

    在代码的实现或者调用上能设定一定的限制和规范,就像契约一样.通常,我们把这种契约称为接口. TypeScript的核心原则之一是对值所具有的结构进行类型检查. 有时称为“鸭式辨型法”或“结构性子类型化 ...

  3. springboot用controller跳转html页面

    之前SSM框架,里面有webapps文件夹,用来存放前端页面和各种前端资源,现在SpringBoot中没有webapps文件夹,springboot结构如下: 第一.resourses下文件夹publ ...

  4. 数位dp踩坑

    前言 数位DP是什么?以前总觉得这个概念很高大上,最近闲的没事,学了一下发现确实挺神奇的. 从一道简单题说起 hdu 2089 "不要62" 一个数字,如果包含'4'或者'62', ...

  5. 【搜索+set去重】Balance Scale

    Balance Scale 题目描述 You, an experimental chemist, have a balance scale and a kit of weights for measu ...

  6. ASP.NET Core 中的脚本标记帮助程序

    官网地址:https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/tag-helpers/built-in/script-tag-helper?v ...

  7. js中prototype与__proto__的关系详解

    一.构造函数: 构造函数:通过new关键字可以用来创建特定类型的对象的函数.比如像Object和Array,两者属于内置的原生的构造函数,在运行时会自动的出现在执行环境中,可以直接使用.如下: var ...

  8. SAP Cloud Platform上Destination属性为odata_gen的具体用途

    今天工作发现,SAP Cloud Platform上创建Destination维护的WebIDEUsage属性很有讲究: 帮助文档:https://help.sap.com/viewer/825270 ...

  9. 使用Mmap系统调用进行硬件地址访问

    Mmap系统调用: Mmap函数是内存映射函数,负责把文件内容映射到进程的虚拟内存空间,通过对这段内存的读取和修改,来实现堆文件的读取和修改,而不需要再调用read,write等操作. 原型如下: 其 ...

  10. 虚拟机和hadoop

    摘要:VMware虚拟机安装Win10,Win10用虚拟机安装教程 微软发布Win10预览版下载地址后,用WMware虚拟机安装Win10是很好的选择.如何用VMware虚拟机安装Win10,Win1 ...