[英]Sorting integers in a csv file - python
I have a csv file that looks like this: 我有一个csv文件,看起来像这样:
Tom,10
Jack,10
Alice,10
Ben,9
I need to be able to sort by the second column from highest to lowest. 我需要能够按从高到低的第二列进行排序。 I have tried the following code:
我尝试了以下代码:
import csv
file = open("bestscores.csv","r")
reader = csv.reader(file, delimiter = ' ')
sort = sorted(reader,key=lambda x: int(x[1]), reverse=True)
print(sort)
This results in the following error: 这将导致以下错误:
ValueError: invalid literal for int() with base 10: 'Tom,10'
How can I solve this? 我该如何解决?
You are using the wrong delimiter and sorting the wrong index. 您使用了错误的定界符,并且对索引进行了排序。 This should work for you:
这应该为您工作:
import csv
with open("bestscores.csv","r") as fh
reader = csv.reader(fh, delimiter = ',')
sort = sorted(reader, key=lambda x: int(x[1]), reverse=True)
print(sort)
You could do like this also, 你也可以这样
with open('file') as f:
print(''.join(sorted(f, key=lambda x: int(x.split(',')[1]), reverse=True)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.