【问题标题】:Numeric sort on two columns but in different order using Python使用 Python 对两列进行数字排序,但顺序不同
【发布时间】:2013-07-04 15:37:08
【问题描述】:

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

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-

【问题讨论】:

    标签: python sorting numeric


    【解决方案1】:

    直接返回负数:

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

    这颠倒了B 的排序顺序,但请注意数据是在A 列上排序的first

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

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

    【讨论】:

    • 谢谢。它就像一个魅力。我已经编辑了答案以供将来参考 - 问题已解决。
    猜你喜欢
    • 1970-01-01
    • 2021-03-27
    • 2019-04-28
    • 2020-06-18
    • 2023-01-19
    • 1970-01-01
    • 2020-09-29
    • 2020-09-04
    • 2017-04-12
    相关资源
    最近更新 更多