Python 对文本文件进行排序?

标签 python python-3.x

所以我知道如何导入 texfile 并对数字进行排序,例如:

1
6
4
6
9
3
5

但我不知道如何对如下所示的数据进行排序:

Merchant_9976 20122
Merchant_9977 91840
Merchant_9978 92739
Merchant_9979 97252
Merchant_9980 76885
Merchant_9981 67835
Merchant_9982 42201
Merchant_9983 47463

这是我到目前为止的代码

def sort_slow(seq):
    for i in range(1, len(seq)):
        j = i
        while j > 0 and seq[j - 1] > seq[j]:
            seq[j - 1], seq[j] = seq[j], seq[j - 1]
            j -= 1
    return seq


def main():
    fileName = str(input('Please enter a filename: '))
    file = open(fileName)
    sort1 = []
    for lines in file:
        sort1.append(int(lines.strip()))
    sort_slow(sort1)
    print(sort1)

main()

我对编码还比较陌生。*大约 1 个月

最佳答案

下面将按右列中的整数排序

with open('file.txt', 'r') as f:
    data = f.readlines()
    sorted_data = sorted(data, key=lambda i: int(i.split()[1]))
    print(sorted_data)

或者,如果您只是希望它们按商家编号排序

with open('file.txt', 'r') as f:
    data = f.readlines()
    sorted_data = sorted(data)
    print(sorted_data)

关于Python 对文本文件进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26246400/

相关文章:

python-3.x - 如何在 Windows 上执行 python 的 Ansible 模块?

python - 如何从 Python 为当前命令提示符 session 设置环境变量

python - sqlalchemy table.update.returning 在 postgresql 上仅返回一个值而不是多个

python - Cython:什么时候应该将字符串定义为 char*、str 或 bytes?

python - 如何在Python中生成运行时类

python - 保留的 Python 模块/包名称是什么?

python - 子类工厂方法的签名

python - flask 属性错误 : module 'app' has no attribute 'run'

CSS 在服务器上的 django 站点管理中不起作用

python pycharm依赖同步