繁体   English   中英

如何将CSV文件中的列表按升序排序?

[英]How would I sort a list from a CSV file in ascending order?

with open('classroom1.csv') as csvfile:
    readCSV = csv.reader(csvfile)
    for row in readCSV:
        name = row[0]
        scores = [int(c) for c in row[1:]]
        total = sum(scores)

到目前为止,这是我的代码,我想按升序对其进行排序。 我知道reverse=True会对我有帮助,但是我不知道如何在这里使用它。

我努力了:

srt = sorted(total, key=lambda x : x[1], reverse=True)
    print(name,srt)

但这不起作用。

我的清单是[userName, score1, score2, score3] ,例如[James, 5, 8, 4] [userName, score1, score2, score3] [James, 5, 8, 4]

如果需要按升序排序,则不应调用reverse=True

如果: classroom1.csv

Ali,100,100
Bob,50,100

并且main.py是:

data=[]
with open('classroom1.csv') as csvfile:
    readCSV = csv.reader(csvfile)
    for row in readCSV:
        name = row[0]
        scores = [int(c) for c in row[1:]]
        total=sum(scores)
        data.append((name,total))
srt=sorted(data, key=lambda x : x[1])
print srt

您将收到:

[('Bob',150),('Ali',200)]
Program to short by userName with high score:
Here  is my cvs file data:

userName, score1,score2,score3
James, 7,3,8
Bob, 9,5,7
Yogi, 10,4,5

import csv
output = {}
first = True
f=open("D:\work\classroom1.cvs")
for row in csv.reader(f):
    if first:
        first = False
        continue
    key = row[0]
    row.pop(0)
    val = list(set(map(int, row)))[0]
    output[key] = val

for key in sorted(output):
    print ("%s, %s" % (key, output[key]))


Output:
>>> ================================ RESTART ================================
>>> 
Bob, 9
James, 8
Yogi, 10

>>>

Program to short by high score:
Here  is my cvs file data:

userName, score1,score2,score3
James, 7,3,8
Bob, 9,5,7
Yogi, 10,4,5
Abhi, 1,2,3

import csv
import operator
output = {}
first = True
f=open("D:\work\classroom1.cvs")
for row in csv.reader(f):
    if first:
        first = False
        continue
    key = row[0]
    row.pop(0)
    val = list(set(map(int, row)))[0]
    output[key] = val

sorted_output = sorted(output.items(), key=operator.itemgetter(1))
for key,val in sorted_output:
    print ("%s, %s" % (key, val))


Output:
>>> ================================ RESTART ================================
>>> 
Abhi, 1
Bob, 9
Yogi, 9
James, 10
>>> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM