含有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>
- l=[(1,2),(2,5),(3,6),(2,7),(2,8)]
- sorted_l=sorted(l,key=lambda t:t[0])
- print(sorted_l)
- sorted_l=sorted(l,key=lambda t:t[1])
- 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的第二位排序