[英]Numeric sort on two columns but in different order using Python
我必须根据两列对多列文件进行排序。 这两列都有浮点数,第一个排序应该从低到高,然后从高到低。 这是示例文件:
A B C D
AK 0.01 200.8 NY
DK 0.90 50.5 PHL
AB 0.0002 750.04 Port
GA 0.076 340.00 NY
所以,我必须先在 B 列上按从低到高的顺序排序,然后在 C 列上按从高到低的顺序排序。 我的代码占用了很多时间,使我的笔记本电脑没有响应,我认为这不应该是这种情况。 此外,我不知道如何在“反向”中对 B 列进行排序,即从高到低。 这是代码:
fh_in = open(res_file,'r')
res = [line.strip('\n').split('\t') for line in fh_in]##Line converted to list and read
res_list = list(res) ##List to hold results while pre-processing
res_list.sort(key= lambda x: (float(x[int(1)]),-float(x[2])))##Sort on Col A and B
print ('Sorted results:\n',res_list)
如何对 B 列从高到低排序的两列进行排序? 实现这一目标的最快方法是什么,因为我有多个文件并且每个文件有 25,000 行 * 50 列?
非常感谢您的帮助。
-AK-
只需返回负数:
res_list.sort(key=lambda x: (float(x[1]), -float(x[2])))
这颠倒了B
排序顺序,但请注意,数据首先在A
列上排序。
请注意,您可以使用sorted()
函数将排序与代码中的上一行结合起来:
res_list = sorted(res, key=lambda x: (float(x[1]), -float(x[2]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.