当前位置:   article > 正文

Python 中 sorted 的用法_pycharm sorted

pycharm sorted

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),] 

(2) 用key 函数排序:返回由tuple 组成的 list

        Python 代码

       

  1. sorted(students, key=lambda student : student[2]) # sort by age
  2. result = [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]

(3) 用cmp 函数排序

         Python 代码

  1. sorted(students, cmp=lambda x,y : cmp(x[2], y[2])) # sort by age
  2. result = [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)]


(4)对字典排序, 返回由tuple 组成的List 不再是字典

         Python 代码

  1. d = {'data1':3, 'data2':1, 'data3':2, 'data4':4}
  2. sorted(d.iteritems(), key=itemgetter(1), reverse=True)
  3. result = [('data4', 4), ('data1', 3), ('data3', 2), ('data2', 1)]


(5)简单排序栗子:

          Python 代码:

  1. #coding:utf-8
  2. input = [[180, 18, 3], [58, 103, 48, 340], [17, 240], [22, 24, 25, 33, 44], [100]]
  3. def seq_sorted(seq):
  4. sort_index = sorted(range(len(seq)), key=lambda x: len(seq[x]))
  5. return sort_index
  6. sort_index = seq_sorted(input)
  7. # print sort_index
  8. out_sentences = [input[i] for i in sort_index]
  9. print out_sentences


执行后可以得到的结果:

  1. /usr/bin/python2.7 /home/yongcai/PycharmProjects/tensorflow/Python/sorted.py
  2. [[100], [17, 240], [180, 18, 3], [58, 103, 48, 340], [22, 24, 25, 33, 44]]





本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号