Home > Backend Development > Python Tutorial > python排序方法实例分析

python排序方法实例分析

WBOY
Release: 2016-06-10 15:13:36
Original
1322 people have browsed it

本文实例讲述了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')]
>>>
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template