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的第二位排序
  • 相关阅读:
    Qt Qaction和触发函数建立连接的方法
    Qt QChart缩放后坐标轴间隔取整
    Qt 编译时报错“退出,退出代码2”的原因
    Qt Qchart 中清空绘图
    Qt QChartView 如何放入widget
    Qt QChart之曲线图,饼状图,条形图使用
    Qt 实现控件不响应鼠标点击事件
    Qt css样式大全(整理版)
    Qt 加载qss文件
    Qt 如何处理密集型耗时的事情(频繁调用QApplication::processEvents)
  • 原文地址:https://www.cnblogs.com/double12gzh/p/10166224.html
Copyright © 2011-2022 走看看