李华用 grade . bxt 来记录学生的成绩,每行有4个正整数,分别用空格分开,每一行的第一列代表学生的学号,第二列代表学生的语文成绩,第三列代表学生的数学成绩,第四列代表学生的总分(学号均用两位数表示,成绩均用三位数表示,不消足两三位的在前面填充0.如89变为089),读取 grade . txt 文件并按要求将结果进行排序,排序后将结果写入 answer . txt .排序要求如下:1.默认先按总分从高到低排序2.当总分相同时按数学成绩从高到低排序3.当语文和数学成绩都相同时则按学生的学号从高到低排序。
dirname = r'C:\Users\Administrator\Desktop'
with open(dirname + '/grade.txt', 'r', encoding = 'utf-8') as f:
v = [list(map(int, i.strip().split("\t"))) for i in f.readlines()]
result = sorted(v, key =lambda x: (x[3], x[2],x[1], x[0]), reverse = True)
res = [list(map(lambda x: str(x).rjust(2, '0'), i)) for i in result]
with open(dirname + '/answer.txt', 'w', encoding = 'utf-8') as f:
for i in res:
print(*i,sep = '\t',file = f )
'grade.txt'
"""00 130 129 259
01 116 092 208
02 092 113 205
03 149 103 252
04 102 135 237
05 117 085 202
06 106 092 198
07 092 122 214
08 146 141 287
09 104 106 210
10 122 135 257
11 111 128 239
12 125 135 260
13 146 099 245
14 111 110 221
15 093 105 198
16 096 101 197
17 135 118 253
18 101 145 246
19 119 118 237
20 118 128 246
21 145 111 256
22 130 093 223
23 094 114 208
24 140 138 278
25 136 144 280
26 092 096 188
27 132 134 266
28 148 129 277"""
'answer.txt'
"""08 146 141 287
25 136 144 280
24 140 138 278
28 148 129 277
27 132 134 266
12 125 135 260
00 130 129 259
10 122 135 257
21 145 111 256
17 135 118 253
03 149 103 252
18 101 145 246
20 118 128 246
13 146 99 245
11 111 128 239
04 102 135 237
19 119 118 237
22 130 93 223
14 111 110 221
07 92 122 214
09 104 106 210
23 94 114 208
01 116 92 208
02 92 113 205
05 117 85 202
15 93 105 198
06 106 92 198
16 96 101 197
26 92 96 188"""
可以放应该文件截图或者吧文件发出来看看吗?
dirBase= r'/home/abc' #你自己定义文件目录,如果设置为"./"表示当前目录
with open(dirBase+ '/grade.txt', 'r', encoding = 'utf-8') as f:
v = [list(map(int, i.strip().split(" "))) for i in f.readlines()] # 用空格隔开需要用空格来split
result = sorted(v, key =lambda x: (x[3], x[2],x[1], x[0]), reverse = True)
res = [[str(i[0]).rjust(2,"0"),str(i[1]).rjust(3,"0"),str(i[2]).rjust(3,"0"),str(i[3]).rjust(3,"0")] for i in result]
with open(dirBase+ '/answer.txt', 'w', encoding = 'utf-8') as f:
for i in res:
print(*i,file = f )