• 含有tuple的list按照tuple中的某一位进行排序


    tuple构成的list可以按照tuple中的任意一位进行排序。
    在python中的例子如下:
    [(13, 1), (11, 1), (9, 1), (6, 1), (1, 1), (2, 1), (4, 1), (13, 1), (4, 1), (2, 1), (13, 1), (0, 1), (7, 1), (11, 2), (9, 2), (6, 2), (1, 2), (2, 2), (13, 2), (2, 2), (8, 2), (12, 2), (13, 2), (0, 2), (7, 2), (4, 3), (13, 3), (5, 3), (5, 3), (4, 3), (6, 3)]
    要将上面的list按照tuple中的第一位升序排列:
    [(0, 1), (0, 2), (1, 1), (1, 2), (2, 1), (2, 1), (2, 2), (2, 2), (4, 1), (4, 1), (4, 3), (4, 3), (5, 3), (5, 3), (6, 1), (6, 2), (6, 3), (7, 1), (7, 2), (8, 2), (9, 1), (9, 2), (11, 1), (11, 2), (12, 2), (13, 1), (13, 1), (13, 1), (13, 2), (13, 2), (13, 3)]

    python中的方法是调用sorted函数,sorted函数可以指定key,用lambda关键字定义“单行最小函数”。单行最小函数是说在一行代码中定义函数,可以看作是内联函数。
    例子:
    <tt class="prompt">>>> </tt><span class="userinput"><span class="pykeyword" style="color:navy;background-color:white; font-weight:bold;">def</span><span class="pyclass" style="color:blue;background-color:white; font-weight:bold;"> f</span>(x):</span>
    <tt class="prompt">...     </tt><span class="userinput"><span class="pykeyword" style="color:navy;background-color:white; font-weight:bold;">return</span> x*2</span>
    <tt class="prompt">...     </tt><span class="userinput"></span>
    <tt class="prompt">>>> </tt><span class="userinput">f(3)</span>
    <span class="computeroutput" style="color:teal;background-color:white;">6</span>
    <tt class="prompt">>>> </tt><span class="userinput">g = <span class="pykeyword" style="color:navy;background-color:white; font-weight:bold;">lambda</span> x: x*2</span>
    <tt class="prompt">>>> </tt><span class="userinput">g(3)</span>
    <span class="computeroutput" style="color:teal;background-color:white;">6</span>
    <tt class="prompt">>>> </tt><span class="userinput"><span class="pykeyword" style="color:navy;background-color:white; font-weight:bold;">(lambda</span> x: x*2)(3)</span>
    <span class="computeroutput" style="color:teal;background-color:white;">6</span>
    1. l=[(1,2),(2,5),(3,6),(2,7),(2,8)]  
    2. sorted_l=sorted(l,key=lambda t:t[0])  
    3. print(sorted_l)  
    4. sorted_l=sorted(l,key=lambda t:t[1])  
    5. print(sorted_l)  

    得到的结果是:
    [(1, 2), (2, 5), (2, 7), (2, 8), (3, 6)] #按照tuple的第一位排序
    [(1, 2), (2, 5), (3, 6), (2, 7), (2, 8)] #按照tuple的第二位排序
  • 相关阅读:
    FreeCAD框架解析
    Python源码的编译与加密
    centos 8及以上安装mysql 8.0
    浮点数运算丢失精度
    使用 Nginx 代理内网 GitLab 并确保 SSH / HTTP 克隆地址正确
    如何实现一个简易版的 Spring
    Spring 是如何造出一个 Bean 的
    从CPU缓存看缓存的套路
    Java 集合类 List 的那些坑
    react 项目中使用antd框架,对导航多层渲染
  • 原文地址:https://www.cnblogs.com/double12gzh/p/10166224.html
Copyright © 2020-2023  润新知