zoukankan      html  css  js  c++  java
  • 含有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的第二位排序
  • 相关阅读:
    MySQL安装失败,提示需安装MicroSoft Visual C++ 2013 Redistributable
    Selinium登录系统cookies的重复使用
    脚本绕开验证码,自动执行的方法
    Firebug显示停用状态
    web自动化测试中绕开验证码登陆的方式
    java使用poi包将数据写入Excel表格
    读取config配置
    定位元素的等待方法
    jxl读取Excel表格数据
    php中的魔术常量
  • 原文地址:https://www.cnblogs.com/double12gzh/p/10166224.html
Copyright © 2011-2022 走看看