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. Java 日期格式工具类

    Java 日期格式工具类 方法如下 DateUtil 类 import java.text.DateFormat; import java.text.ParseException; import ja ...

  2. C++:标准模板库Sort

    一.概述 STL几乎封装了所用的数据结构中的算法,这里主要介绍排序算法的使用,指定排序迭代器区间后,即可实现排序功能. 所需头文件#include <algorithm> sort函数:对 ...

  3. 3种PHP实现数据采集的方法

    https://www.php.cn/php-weizijiaocheng-387992.html

  4. 2020企业python真面试题持续更新中

    目录 1.软件的生命周期 2.如何知道一个python对象的类型 3.简述Django的设计模式MVC,以及你对各层的理解和用途 4.什么是lambda函数,说明其使用场景 5.python是否支持函 ...

  5. PAT(B) 1021 个位数统计(Java)

    题目链接:1021 个位数统计 (15 point(s)) 代码 /** * Score 15 * Run Time 93ms * @author wowpH * @version 1.0 */ im ...

  6. Java中将字符串用空格分割成字符串数组的split方法

    官方文档链接:public String[] split(String regex) 本文以空格作为分割串. CaseOne import java.util.Scanner; public clas ...

  7. WUSTOJ 1239: n皇后问题(Java)

    题目链接:

  8. go defer 语句会延迟函数的执行直到上层函数返回。

    defer code... 可以理解为 执行完当前defer所在的方法代码后执行defer 中的代码 常用在释放资源 比如 关闭文件 为防止忘记编写关闭代码 可以先写好   defer  各种释放资源 ...

  9. sqlite3 下载和安装步骤

    1 下载地址 https://www.sqlite.org/2019/sqlite-tools-win32-x86-3300100.zip 2 添加系统变量 path中添加  sqlite3.exe所 ...

  10. 0160 十分钟看懂时序数据库(I)-存储

    摘要:2017年时序数据库忽然火了起来.开年2月Facebook开源了beringei时序数据库:到了4月基于PostgreSQL打造的时序数据库TimeScaleDB也开源了,而早在2016年7月, ...