【发布时间】:2022-01-05 19:24:45
【问题描述】:
在这段代码中,必须对元组进行排序,但我问用户想要什么样的排序,但这个问题被问了四次:
students = (("st_1", "a", "40"),
("st_2", "b", "38"),
("st_3", "c", "32"),
("st_4", "a", "10"))
def key_sort(keys):
index = 0
what_sort = input("do you sort a list ? n for name , g for grade and a for age : ").lower()
if what_sort == 'a':
index = keys[2]
elif what_sort == 'n':
index = keys[0]
elif what_sort == 'g':
index = keys[1]
return index
sorted_students = sorted(students, key=key_sort)
for i in sorted_students:
print(i)
为什么要问四次? terminal result
【问题讨论】:
-
因为 key_sort 会为列表中的每个项目调用...
-
预先输入并调用函数,然后将值传递给排序
标签: python function sorting tuples