我正在尝试创建基于最高值的某种记分板。我已经添加了reverse=true标志,但它仍然打印为升序而不是降序。我也尝试过更改代码以使用sort()方法,但似乎就是不起作用。
def sort(results):
import csv
import operator
sort = open(results,'r')
newsort = sorted(sort,key=operator.itemgetter(1), reverse = True)
for eachline in newsort:
print (eachline)鲍勃,5岁,记忆力
Blod,1,内存
凯蒂,5岁,记忆
糖果,4,记忆
Candice,1,内存
Candybdjf,5,内存
什么是打印的,即使我要求它按索引1排序?
发布于 2018-08-19 06:19:04
我认为你想要这样的东西(假设你的第二个列名是'Idx'):
with open('test.csv', 'r') as csvfile:
reader = csv.DictReader(csvfile)
for row in sorted(reader, key=operator.itemgetter('Idx'), reverse=True):
print(row)输出:
OrderedDict([('Name', 'Bob'), ('Idx', '5'), ('Memory', 'memory')])
OrderedDict([('Name', 'candy'), ('Idx', '5'), ('Memory', 'memory')])
OrderedDict([('Name', 'Candy'), ('Idx', '4'), ('Memory', 'memory')])如果你不想使用csv阅读器,你可以尝试这样做:
with open('test.csv', 'r') as csvfile:
for row in sorted(csvfile, key=lambda x: x.split(',')[1], reverse=True):
print(row)输出:
Bob,5,memory
candy,5,memory
Candy,4,memoryhttps://stackoverflow.com/questions/51912909
复制相似问题