effective python-Item 14

list.sort函数,比较容易用的是reverse,而其中还有个参数key,默认是NONE,此时排序是按照默认比较方法排序,比如数据按照大小,字符串按照字符的顺序,这种python中存在的数据类型,比较起来还是比较简单的。但是如果你比较的是objects,比较复杂,不能再按照数据大小或者字符串顺序比较排序时,怎么办呢?你需要给你的比较对象指定排序方法。比如两个人,怎么排序?比较年龄还是比较姓名进行排序?这就是key发挥作用的时候了,此时通过key这个参数指定我们要做排序的objects,是用什么方法来排序,按照人名还是年龄还是体重还是身高还是颜值呢?因此key这个参数需要的是function,这个func完成排序的方法。

## Item 14: Sort by Complex Criteria Using `key` Parameter
"""
* Use `sort()` method to sort built-in types which has
a natural ordering to them: """
numbers = [93, 46, 75, 33, 0, 23, 33]
numbers.sort()
print(numbers)

  

"""
* `sort()` do not work directly on objects.
You need to use `key` parameter, which accepts function:
"""
class Tool():
def __init__(self, name, weight):
self.name = name
self.weight = weight def __repr__(self):
return f"Tool({self.name!r}, {self.weight})" tools = [
Tool("level", 3.5),
Tool("hammer", 1.25),
Tool("screwdriver", 0.5),
Tool("chisel", 0.25),
] print("Unsorted:", repr(tools))
tools.sort(key=lambda x: x.name) # ordered by x.name
print("\nSorted:", tools) # In[]
"""
* For `str` you may want to lower case each item in a
list to ensure that they are in alphabetical order
""" places = ["home", "work", "New York", "Paris"]
places.sort()
print("Case sensitive:", places)
places.sort(key=lambda x: x.lower())
print("Case insensitive:", places)

* for sorting with multiple criteria you may use `key` parameter

returning `tuple` containing two attributes in required order:

tuple 实现按照多个指标进行排序的目的,先按照第一个元素排序,然后第二个,但是不管有多少个排序指标,排序的先后顺序(从小到大,从大到小等)都一样,因为reverse是作用在所有指标上的。如果某一个元素是可否定(negation),则可以在这个指标前加个-,实现顺序和reverse设定的是反过来的。但是并不是所有元素都可以这么做,比如下面例题中,x.name字符串是没办法加-进行否定的。此时就不可以这么做,但是x.weight可以,因为是数值,可以加-。此时如果你想按照两个指标进行排序,那么不能再用tuple这种方式了,你可以把各个指标分开对objects进行排序,先按照lowest的元素进行排序,再按照highest的元素进行排序。

power_tools = [
Tool('drill', 4),
Tool('circular saw', 5),
Tool('jackhammer', 40),
Tool('sander', 4),
] power_tools.sort(key=lambda x: (x.weight, x.name))
print(power_tools)
"""
* Negation on `int`'s may be used to sort in different directions:
"""
power_tools.sort(key=lambda x: (-x.weight, x.name))
print(power_tools)
""""
* To combine mane sorting criteria and different directions
combine `sort` function calls following way and use `reverse`
for changing direction: """
power_tools.sort(key=lambda x: x.name)
power_tools.sort(key=lambda x: x.weight, reverse=True)
print(power_tools)

  

  

effective-python-14的更多相关文章

  1. Effective Python之编写高质量Python代码的59个有效方法

                                                         这个周末断断续续的阅读完了<Effective Python之编写高质量Python代码 ...

  2. Effective Python 中文版

    如题,博主正在翻译一本Python相关的书. 图为Python作者. [美]Brett Slatkin的名作. Effective Python: 59 Specific Ways to Write ...

  3. 《Effective Python:编写高质量Python代码的59个有效方法》读书笔记(完结)

    Effective Python 第1章 用Pythonic方式来思考 be pythonic 遵守pep8 python3有两种字符序列类型:bytes(原始的字节)和str(Unicode字符). ...

  4. [Effective Python] 用Pythonic方式来思考

    Effective Python chap.1 用Pythonic方式来思考 Pythonic: 一门语言的编程习惯是由用户来确立的. 1. 确认自己所使用的Python版本 2. 遵循PEP8风格指 ...

  5. Effective Python 编写高质量Python代码的59个有效方法

    Effective Python 编写高质量Python代码的59个有效方法

  6. Python -- Effective Python:编写高质量Python代码的59个有效方法

    第 1 章 用 Pythonic 方式来思考 第 1 条:确认自己所用的 Python 版本 python --version import sys print(sys.version_info) p ...

  7. [Advanced Python] 14 - "Generator": calculating prime

    高性能编程 几个核心问题 • 生成器是怎样节约内存的?• 使用生成器的最佳时机是什么?• 我如何使用 itertools 来创建复杂的生成器工作流?• 延迟估值何时有益,何时无益? From: htt ...

  8. Effective Python读书笔记

    有些位置可能翻译理解的不到位,各位看官如有疑问,欢迎留言赐教. Pythonic Thinking 大家经常用Pythonic来形容python语法风格的编程方式:简单优美,没有之一:通过import ...

  9. Effective python(五):内置模块

    1,考虑使用contextlib和with语句改写可复用的try/finally代码 with lock:print('lock is held')相当于try:print('lock is held ...

  10. [LeetCode][Python]14: Longest Common Prefix

    # -*- coding: utf8 -*-'''__author__ = 'dabay.wang@gmail.com'https://oj.leetcode.com/problems/longest ...

随机推荐

  1. yb课堂实战之接口协议调整和日期格式 《十八》

    调整api接口协议和日期格式 统一输出协议,驼峰转下划线 格式化日期

  2. CGI,FastCGI和PHP-FPM之间的关系和区别

    什么是CGI?早期的web server只可以处理简单的静态web文件,但是随着技术的发展出现动态语言如PHP,Python.PHP语言交给PHP解析器进行处理,但是处理之后如何和web server ...

  3. 字符—字符与整数的关系&&常用的库函数_C

    // Code file created by C Code Develop #include "ccd.h" #include "stdio.h" #incl ...

  4. 使用JavaScript编写vue指令v-model,v-model原理实现

    首先先要知道的是v-model的作用是实现数据的双向绑定,即: 数据在视图层的双向响应. 实现思路主要分为两步: 第一步:数据层到视图层的响应 将数据响应到视图层的方式,在vue2使用的是Object ...

  5. PHP转Go系列 | 推荐一个强大的Go语言工具函数库

    大家好,我是码农先森. 从 PHP 转到 Go 的朋友,常常会因为没有便捷的工具函数而感到苦恼.PHP 写的多了就会形成路径依赖,在写 Go 的时候时不时就会想到 PHP 强大的数组函数.当然写 Go ...

  6. 测试工程师-年终总结PPT

    2022年年终总结-xxx 一.首页 2022年年终总结暨2023年工作计划 汇报人:测试组-xxx 日期: 2023.1.13 二.目录 1.年度工作概述 2.工作亮点展示 3.持续精进点 4.明年 ...

  7. vue加载三维模型

    创建项目 我使用的是Vue CLI3,具体创建不再赘述,网上教程很多 下载SuperMap iClient3D for WebGL产品包 链接:http://support.supermap.com. ...

  8. 【SpringBoot】10 Web开发 Part1 静态资源

    使用SpringBoot创建工程的方式: 1.在IDEA集成的Boot官网选项中点选可能需要的框架环境即可 2.SpringBoot已经设置好了这些场景,只需要配置文件中指定少量配置就可以运行起来 3 ...

  9. 【Vue】Re07 插槽Slot

    一.插槽基本使用 <!DOCTYPE html> <html lang="en"> <head> <meta charset=" ...

  10. ECMO(体外膜氧合)的使用费用为什么会这么高?

    给一个大致的费用: 相关: https://www.bilibili.com/video/BV1rc411H7uT/ https://haokan.baidu.com/v?pd=wisenatural ...