python排序方法实例分析

yipeiwu_com6年前Python基础

本文实例讲述了python排序方法。分享给大家供大家参考。具体如下:

>>> def my_key1(x):
...   return x % 10
...
>>> alist = [4, 5, 8, 1, 63, 8]
>>> alist
[4, 5, 8, 1, 63, 8]
>>> alist.sort() # 默认升序排序
>>> alist
[1, 4, 5, 8, 8, 63]
>>> alist.sort(reverse = True) # 改为降序排序
>>> alist
[63, 8, 8, 5, 4, 1]
>>> alist.sort(key = my_key1) # 设置排序的key值
>>> alist
[1, 63, 4, 5, 8, 8]
>>>
>>> def my_key2(x):
...   return x[1]
...
>>> alist = [(5,'a'),(1,'w'),(2,'e'),(6,'f')]
>>> alist.sort(key = my_key2) # 根据每个元组的第二分量进行排序
>>> alist
[(5, 'a'), (2, 'e'), (6, 'f'), (1, 'w')]
>>>

希望本文所述对大家的Python程序设计有所帮助。

相关文章

树莓派用python中的OpenCV输出USB摄像头画面

树莓派用python中的OpenCV输出USB摄像头画面

本文实例为大家分享了python OpenCV来表示USB摄像头画面的具体代码,供大家参考,具体内容如下 确认Python版本 $ python Python 2.7.13 (def...

Django 导出项目依赖库到 requirements.txt过程解析

虚拟环境: 使用 pip freeze pip freeze > requirements.txt # 这种方式推荐配合 virtualenv ,否则会把整个环境中的包都列...

python 字符串常用函数详解

字符串常用函数: 声明变量 str="Hello World" find() 检测字符串是否包含,返回该字符串位置,如果不包含返回-1 str.find("Hello") # 返回值...

Django数据库连接丢失问题的解决方法

问题 在Django中使用mysql偶尔会出现数据库连接丢失的情况,错误通常有如下两种 OperationalError: (2006, 'MySQL server has gon...

Python基础知识点 初识Python.md

Python基础知识点 初识Python.md

Python简介 Python的历史 1989年圣诞节:Guido von Rossum开始写Python语言的编译器。 1991年2月:第一个Python编译器(同时也是解释器)...