【发布时间】:2021-09-19 18:55:26
【问题描述】:
我正在尝试对嵌套列表进行排序。我有一个这样的输入文件:
曼陀罗,5,7,3,15
阿里,19,10,19,6,8,14,3
hamid,3,9,4,20,9,1,8,16,0,5,2,4,7,2,1
索拉布,19,10,19,6,8,14,3
萨拉,0,5,20,14
索黑拉,13,2,5,1,3,10,12,4,13,17,7,7
纳希德,13,2,5,1,3,10,12,4,13,17,7,7
阿里,1,9
萨文,0,16,16,13,19,2,17,8
谢达,0,16,16,13,19,2,17,8
当我用函数排序时
def calculate_sorted_averages(input_file_name,output_file_name):
with open (input_file_name) as f:
reader=csv.reader(f)
list1=list()
for row in reader:
name=row[0]
these_grade=list()
for grade in row[1:]:
these_grade.append(float(grade))
avg1=mean(these_grade)
list1.append([name,avg1])
print(list1)
**list1.sort(key=lambda x: (int(x[1]), x[0]))**
print(list1)
with open (output_file_name,'w',newline='') as outp:
writer = csv.writer(outp)
for item in list1:
writer.writerow(item)
outp.close()
输出文件是:
阿里,5.0
哈米德,6.066666666666666
曼陀罗,7.5
纳希德,7.833333333333333
索黑拉,7.833333333333333
萨拉,9.75
阿里,11.285714285714286
萨文,11.375
谢达,11.375
索拉布,11.285714285714286
Sohrab 在排序中不正确。但是当我更改 Sohrab'name 例如 Nima 时,排序是正确的。 我该如何解决这个问题?
【问题讨论】:
标签: python python-3.x list average nested-lists