python - 对值进行排序并查找最佳分数(最高数字)

标签 python

我刚刚开始学习Python,如果有人愿意提供帮助,我需要一些帮助、技巧或解决方案。

我有一个如下所示的文件:

    2  C00000002 score:  -48.649 nathvy =  49 nconfs =         3878
    3  C00000001 score:  -44.988 nathvy =  41 nconfs =         1988
    4  C00000002 score:  -42.674 nathvy =  49 nconfs =         6740
    5  C00000002 score:  -42.453 nathvy =  49 nconfs =         4553
    6  C00000002 score:  -41.829 nathvy =  49 nconfs =         7559
    7  C00000002 score:  -41.156 nathvy =  49 nconfs =         2251
    8  C00000002 score:  -39.520 nathvy =  49 nconfs =         3129
    9  C00000004 score:  -38.928 nathvy =  24 nconfs =          150
   10  C00000002 score:  -38.454 nathvy =  49 nconfs =         9473
   11  C00000004 score:  -37.704 nathvy =  24 nconfs =          156
   12  C00000001 score:  -37.558 nathvy =  41 nconfs =           51

我的第二列是一些此处未排序的 ID,其中一些是重复的,例如 (C00000001)。所有这些都分配有不同的数字,后跟 score:(数字通常以 - 开头)。

我想做的是:
1)读取第二列(未排序的ID)并始终选择出现的第一列。因此,在 C00000001 的情况下,它将选择 score : -44.988

2)现在,当我提供唯一值时,我想根据 score: 之后的数字对它们进行排序,这意味着最大负数位于第一个位置,而最大正数位于第一个位置处于最后一个位置。

最佳答案

您可以使用简单的 python 来完成此操作。 Python列表内置排序方法

with open("in_file") as handle:
    already_present = set()
    l = []
    for line in handle:
        line_parts = line.strip().split()
        l.append(line_parts)
        key = line_parts[1]
        if key in already_present:
            continue
        already_present.add(key)

l.sort(key=lambda x:float(x[3]))

关于python - 对值进行排序并查找最佳分数(最高数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52158573/

相关文章:

python - Pandas - 添加一列,其值是根据当前行和上一行中的另一列值计算的

python - 新建 Postgresql 数据库 : column "id" is of type integer but expression is of type uuid when creating super user

python - 在 Python 中使用索引删除项目的就地函数

python - 如何使用 python 重命名文件夹中的多个文件?

python:array([...]) 是什么意思?

python - 使用py2exe后消息框立即关闭

python - 连接到 0.0.0.0 上的测试 SFTP 服务器

python - 在 Python 中导入模块 - 推荐位置

python - numpy中轴的长度是多少

python - virtualenv 挂断了安装 setuptools