Python:如何按数字顺序对 .txt 文件的内容进行排序? [英] Python: How do you sort the contents of a .txt file in numerical order?

查看:66
本文介绍了Python:如何按数字顺序对 .txt 文件的内容进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写按数字顺序排列 .txt 文件的代码时遇到了一些麻烦.

I have some trouble making a code that arranges a .txt file in numerical order.

我遇到的问题是,在 .txt 文件中订购数字 77、45、85、100 时,它会将其订购为 100、45、77、85;100 是最低的.

The problem I'm having is when ordering numbers 77, 45, 85, 100 in the .txt file it orders it as 100, 45, 77, 85; 100 being the lowest.

不确定我会如何更正,因为我希望 100 是最高的.

Not sure how I would correct that as I want 100 to be the highest.

这是我目前所拥有的:

import csv
import operator


sample = open("score.txt")
csv1 = csv.reader(sample, delimiter=',')
sort = sorted(csv1, key=operator.itemgetter(1))
for eachline in sort:
    print eachline

推荐答案

就像budder 所说的那样,尝试将您的元素转换为intfloat.假设您正在使用整数,您可以在 sorted() func:

Like budder says, try to convert your elements to int or float. Assuming that your are working with integers you can change your key in sorted() func:

sort = sorted(csv1, key=lambda x : int(x[1]))

这篇关于Python:如何按数字顺序对 .txt 文件的内容进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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