问题
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