我正在编写代码来查找目录中所有文件的平均值,将它们保存到列表中,然后按平均数排序。例如,文件列表是['我','你','他','她']
和得分列表是[' 4.67',' 5.33',' 6.33',' 5.33']
这使student_average_list ['我:4.67','你:5.33','他:6.33','她:5.33 &#39]。
我想对它进行排序,以便它成为['他:6.33','你:5.33','他:5.33',& #39;我:4.67']。
没有语法错误,它只是错误地排序。感谢您的帮助
def sort_average():
scores = []
student_average_list = []
for file in os.listdir(path):
file = os.path.join(path, file)
if os.path.isfile(file):
with open(file, 'r') as txt_file:
data = [float(line.rstrip()) for line in txt_file]
average = (sum(data) / len(data))
average = ("{0:.2f}".format(average))
scores.append(str(average))
for x, y in zip(files, scores):
student_result = (x + ": " + y)
student_average_list.append(student_result)
student_average_list.sort(key=lambda x: float(x[-1]), reverse=True)
print(student_average_list)
答案 0 :(得分:1)
我会替换
for x, y in zip(files, scores):
student_result = (x + ": " + y)
student_average_list.append(student_result)
student_average_list.sort(key=lambda x: float(x[-1]), reverse=True)
print(student_average_list)
使用
import operator
results = zip(files, map(float, scores))
results = sorted(results, key=operator.itemgetter(1), reverse=True)
student_average_list = ["{}: {:.2f}".format(x, y) for x, y in results]
print(student_average_list)
这样您就可以在转换为字符串之前创建排序列表。这将使它变得更容易。
无需将分数转换为中间的字符串。这是一种浪费。