zoukankan      html  css  js  c++  java
  • Python中List的排序

    Python对List的排序主要有两种方法:一种是用sorted()函数,这种函数要求用一个变量接收排序的结果,才能实现排序;另一种是用List自带的sort()函数,这种方法不需要用一个变量接收排序的结果.这两种方法的参数都差不多,都有key和reverse两个参数,sorted()多了一个排序对象的参数.

    1. List的元素是变量

    这种排序比较简单,直接用sorted()或者sort()就行了.

    list_sample = [1, 5, 6, 3, 7]
    # list_sample = sorted(list_sample)
    list_sample.sort(reverse=True)
    print(list_sample)

    运行结果:

    [7, 6, 5, 3, 1]

    2. List的元素是Tuple

    这是需要用key和lambda指明是根据Tuple的哪一个元素排序.

    list_sample = [('a', 3, 1), ('c', 4, 5), ('e', 5, 6), ('d', 2, 3), ('b', 8, 7)]
    # list_sample = sorted(list_sample, key=lambda x: x[2], reverse=True)
    list_sample.sort(key=lambda x: x[2], reverse=True)
    print(list_sample)

    运行结果:

    [('b', 8, 7), 
    ('e', 5, 6),
    ('c', 4, 5),
    ('d', 2, 3),
    ('a', 3, 1)]

    3. List的元素是Dictionary

    这是需要用get()函数指明是根据Dictionary的哪一个元素排序.

    list_sample = []
    list_sample.append({'No': 1, 'Name': 'Tom', 'Age': 21, 'Height': 1.75})
    list_sample.append({'No': 3, 'Name': 'Mike', 'Age': 18, 'Height': 1.78})
    list_sample.append({'No': 5, 'Name': 'Jack', 'Age': 19, 'Height': 1.71})
    list_sample.append({'No': 4, 'Name': 'Kate', 'Age': 23, 'Height': 1.65})
    list_sample.append({'No': 2, 'Name': 'Alice', 'Age': 20, 'Height': 1.62})
    list_sample = sorted(list_sample, key=lambda k: (k.get('Name')), reverse=True)
    # list_sample.sort(key=lambda k: (k.get('Name')), reverse=True)
    print(list_sample)

    运行结果:

    [{'No': 1, 'Name': 'Tom', 'Age': 21, 'Height': 1.75}, 
    {'No': 3, 'Name': 'Mike', 'Age': 18, 'Height': 1.78},
    {'No': 4, 'Name': 'Kate', 'Age': 23, 'Height': 1.65},
    {'No': 5, 'Name': 'Jack', 'Age': 19, 'Height': 1.71},
    {'No': 2, 'Name': 'Alice', 'Age': 20, 'Height': 1.62}]
  • 相关阅读:
    Android学习笔记之-----讯飞语音识别实例化RecognizerDialog参数出现错误的解决方法
    java基本数据类型取值范围
    中国教育
    git push --help
    cherry Tree的严重漏洞
    程序的核心是什么
    BeanUtils.getProperty性能分析
    Java各种反射性能对比
    Spring AOP无法拦截Controller中的方法
    Mock单元测试
  • 原文地址:https://www.cnblogs.com/mstk/p/12810138.html
Copyright © 2011-2022 走看看