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]
答案 0 :(得分:2)
如果您需要按升序排序,则不应拨打reverse=True
if: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)]
答案 1 :(得分:0)
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
>>>