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. time模块/datetime模块/calendar模块

    time模块时间的表示形式时间戳:以整型或浮点型表示⼀个时间,该时间以秒为单位,这个时间是以1970年1⽉1⽇0时0分0秒开始计算的. 导入time import time 1.返回当前的时间戳 no ...

  2. SAS学习笔记12 SAS数据清洗和加工

    set语句纵向合并 我们把a1和b1进行合并,并区分是来自哪个数据集,会用到in=选项 in=a是产生临时变量a,由于它是a1的选项,所以a的值=1(来自a1)或者=0(不来自a1) in=b是产生临 ...

  3. c++学习总结(一)------类结构学习

    基类的构造函数并没有被派生类继承 析构函数和拷贝赋值操作符同样也没有 类的设计者通过把成员函数声明为 const 以表明它们不修改类对象 把一个修改类数据成员的函数声明为 const 是非法的 (51 ...

  4. kettle工具的介绍和使用

    kettle详解(数据抽取.转换.装载) 原文地址链接:https://blog.csdn.net/qq_35731570/article/details/71123413   一:下载路径 当你要学 ...

  5. IOS+H5页面自定义按钮无效

    在IOS整合H5页面的时候,自定义的按钮失去效果,Android系统可以. 如图,确定和取消按钮在IOS系统无效. 解决办法是在两个按钮上加上一个style属性即可 <span class=&q ...

  6. (五)CXF之添加拦截器

    一.需求分析 webService中的拦截器类似于servlet的Filter过滤器.一般用于调用服务前后先调用拦截器的方法. 二.案例 本章案例是基于上一章节的基础上添加拦截器的 2.1 服务端添加 ...

  7. (四)网格(dataGrid)

    一.普通网格 前端index.jsp <%@ page language="java" contentType="text/html; charset=UTF-8& ...

  8. Html5+Mui前端框架,开发记录(四):下拉菜单绑定数据、搜索、时间控件

    1.下拉菜单绑定数据,选择后回传值 1)html: <div class="mui-input-row"> <label>xxx:</label> ...

  9. regarding-hsts-in-netscaler

    regarding-hsts-in-netscaler 参考: Strict Transport Security (STS or HSTS) with Citrix NetScaler and Ac ...

  10. jQuery_了解jQuery