使用 Python 对两列进行数字排序,但顺序不同 [英] Numeric sort on two columns but in different order using Python

查看:96
本文介绍了使用 Python 对两列进行数字排序,但顺序不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须根据两列对多列文件进行排序.这两列都有浮点数,第一个排序应该从低到高,然后从高到低.这是示例文件:

I have to sort a multi-column file based on two columns. Both the columns have floating point numbers and first sort should from lower to higher and second on higher to lower. Here is sample file:

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 列进行排序,即从高到低.代码如下:

So, I have to sort on column B first in order low to high and then on column C in order high to low. The code I have is taking a lot of time and make my laptop unresponsive which I believe should not be the case. Moreover, I do not how can I sort column B in 'reverse' i.e. High to low. Here is the code:

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 列?

How can I sort on both columns with column B sorted from High to low? What would be the fastest way to achieve so, as I have multiple files and each file has 25,000 rows*50 columns?

非常感谢您的帮助.

-AK-

推荐答案

只需返回负数:

res_list.sort(key=lambda x: (float(x[1]), -float(x[2])))

这与 B 的排序顺序相反,但请注意数据在列 A first 上排序.

This reverses the B sort order, but do note that the data is sorted on column A first.

请注意,您可以使用 sorted() 函数将排序与代码中的前一行结合起来:

Note that you can combine the sorting with the previous line in your code by using the sorted() function:

res_list = sorted(res, key=lambda x: (float(x[1]), -float(x[2]))

这篇关于使用 Python 对两列进行数字排序,但顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆