我有一本包含清单的字典
students = {
1:["name1", 20, 100],
2:["name2", 20, 100],
3:["name3", 20, 95],
4:["name4", 21, 65],
5:["name5", 22, 85]
}
我想创建表并按名称对数据进行排序。像这样
Name Age Score
name1 20 100
name2 20 100
name3 20 95
name4 21 65
name5 22 85
我该怎么做? 我这样写:
students = {
1:["Rauf", 20, 100],
2:["Shafag", 20, 100],
3:["Ali", 20, 95],
4:["Camal", 21, 65],
5:["Arzu", 22, 85]
}
print(" ")
print("{:>12} {:>12} {:>12}".format('Name','Age','Score'))
print(" ")
for v in students.values():
name, age, score = v
print(sorted(("{:>12} {:>12} {:>12}".format(name, age, score)), key= lambda v: v[2]))
答案 0 :(得分:1)
此帮助
import operator
students = {
1:["Rauf", 20, 100],
2:["Shafag", 20, 100],
3:["Ali", 20, 95],
4:["Camal", 21, 65],
5:["Arzu", 22, 85]
}
print(" ")
print("{:>12} {:>12} {:>12}".format('Name','Age','Score'))
sorted_students = sorted(students.items(), key=operator.itemgetter(1))
print(" ")
for v in sorted_students:
name, age, score = v[1]
print("{:>12} {:>12} {:>12}".format(name, age, score))
答案 1 :(得分:0)
使用f字符串(Python 3.6+)和map
,您可以简化语法并提高代码效率。您需要sorted
才能按名称排序。
import operator
students = {1:["Rauf", 20, 100],
2:["Shafag", 20, 100],
3:["Ali", 20, 95],
4:["Camal", 21, 65],
5:["Arzu", 22, 85]}
print(" ")
print(f"{'Name':>12} {'Age':>12} {'Score':>12}")
sorted_students = sorted(students.items(), key=operator.itemgetter(1))
print(" ")
for name, age, score in map(itemgetter(1), sorted_students):
print(f"{name:>12} {age:>12} {score:>12}")
结果:
Name Age Score
Ali 20 95
Arzu 22 85
Camal 21 65
Rauf 20 100
Shafag 20 100