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+selenium 点击单选框-radio的实现方法

例子:以百度文库中选择文档的类型为例 问题一:遍历点击所有文档类型的单选框 # coding=utf-8 from selenium import webdriver from t...

Python使用matplotlib填充图形指定区域代码示例

Python使用matplotlib填充图形指定区域代码示例

本文代码重点在于演示Python扩展库matplotlib.pyplot中fill_between()函数的用法。 import numpy as np import matplot...

pytorch 常用线性函数详解

Pytorch的线性函数主要封装了Blas和Lapack,其用法和接口都与之类似。 常用的线性函数如下: 函数 功能...

关于python中plt.hist参数的使用详解

关于python中plt.hist参数的使用详解

如下所示: matplotlib.pyplot.hist( x, bins=10, range=None, normed=False, weights=None, c...

Python全排列操作实例分析

本文实例讲述了Python全排列操作。分享给大家供大家参考,具体如下: step 1: 列表的全排列: 这个版本比较low # -*-coding:utf-8 -*- #!pytho...