Python: How do you sort the contents of a .txt file in numerical order? [duplicate]

别等时光非礼了梦想. 提交于 2021-02-04 07:18:46

问题


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

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.

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

This is what I have so far:

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

回答1:


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]))



回答2:


You need to sort them numerically instead of alphabetically.

Try this:

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



回答3:


The entries need to first be converted to integers to be correctly sorted.

score.txt

312
148
17
108

python

with open('score.txt', 'r') as f:
    lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()
print numbers

#[17, 108, 148, 312]


来源:https://stackoverflow.com/questions/32833226/python-how-do-you-sort-the-contents-of-a-txt-file-in-numerical-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!