赞
踩
sorted 排序方法主要是用在 list 和 dict 中。
sorted 介绍:
其中, iterable 是可迭代类型
cmp 是用于比较的函数,比较什么由key 决定
key 是列表元素的某个属性或函数进行作为关键字,有默认值,迭代集合中的一项
reverse 是排序规则,reverse = True 表示降序, reverse= False 表示升序,有默认值
返回值 是一个经过排序的可迭代类型,与iterable 一样
栗子:
(1)对由tuple 组成的List 排序
Python 代码
students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10),]
Python 代码
- sorted(students, key=lambda student : student[2]) # sort by age
-
- result = [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
Python 代码
- sorted(students, cmp=lambda x,y : cmp(x[2], y[2])) # sort by age
-
- result = [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]
(4)对字典排序, 返回由tuple 组成的List 不再是字典
Python 代码
- d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}
- sorted(d.iteritems(), key=itemgetter(1), reverse=True)
-
- result = [('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]
(5)简单排序栗子:
Python 代码:
- #coding:utf-8
-
-
- input = [[180, 18, 3], [58, 103, 48, 340], [17, 240], [22, 24, 25, 33, 44], [100]]
-
- def seq_sorted(seq):
- sort_index = sorted(range(len(seq)), key=lambda x: len(seq[x]))
- return sort_index
-
-
- sort_index = seq_sorted(input)
- # print sort_index
-
- out_sentences = [input[i] for i in sort_index]
- print out_sentences
执行后可以得到的结果:
- /usr/bin/python2.7 /home/yongcai/PycharmProjects/tensorflow/Python/sorted.py
- [[100], [17, 240], [180, 18, 3], [58, 103, 48, 340], [22, 24, 25, 33, 44]]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。