元组的python上的sorted()函数



在这段代码中,元组必须排序,但我问了一个用户想要什么样的排序的问题,但这个问题问了四次:

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)

为什么要问四次这个问题?终端结果

首先询问,然后构造一个适当的函数传递给sorted

from operator import itemgetter
what_sort = input("do you sort a list ? n for name , g for grade and a for age : ").lower()
if what_sort == 'a':
n = 2
elif what_sort == 'n':
n = 0
elif what_sort == 'g':
n = 1
else:
n = 0  # Pick a good default      

sorted_students = sorted(students, key=itemgetter(n))

key=key_sort表示对于每个项keysorted()函数将调用key_sort(key)来确定该键的排序顺序。该函数中有一个input(),如果列表中有4个项,则意味着key_sort()将被调用4次。这只是Python按照设计工作。如果您希望输入不是每次都运行,则必须使用某种条件。或者,更有意义的是事先询问排序方法,然后设置key_sort随后使用的类或全局变量what_sort

正如@Joran Beasley所指出的,sorted中的key参数被调用到要排序的迭代中的每个元素(在您的例子中,是变量students(。

获得您所要求的行为的一种方法是修改key_sort函数以返回另一个函数,该函数应用作sorted调用中的key参数。

请考虑以下代码

students = (("st_1", "a", "40"),
("st_2", "b", "38"),
("st_3", "c", "32"),
("st_4", "a", "10"))
def key_sort():
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 = 2
elif what_sort == 'n':
index = 0
elif what_sort == 'g':
index = 1
return lambda student: student[index]
key_fn = key_sort()
sorted_students = sorted(students, key=key_fn)
for i in sorted_students:    
print(i)

这样,用户交互(input函数调用(将只运行一次。

sorted函数中的key参数是用于获取要排序的值的函数的名称。例如,在整数列表中,这是不必要的,因为对象本身当然可以直接进行比较和排序。但对于元组,还不清楚应该如何比较它们。使用第一个元素?最后一个?所有这些都混在一起?Python无法回答这个问题。key存在,因此您可以指定如何执行。

解决特定问题的方法是首先向用户提问,然后使用他们的答案来选择如何对列表进行排序。有很多方法可以做到这一点,但以下是我认为最简单的方法。

students = (("st_1", "a", "40"),
("st_2", "b", "38"),
("st_3", "c", "32"),
("st_4", "a", "10"))
def get_name(student):
return student[0]
def get_grade(student):
return student[1]
def get_age(student):
return student[2]
sort_index = input("How should the list be sorted? (n for name , g for grade and a for age) : ").lower()
if sort_index == 'n':
sorted_students = sorted(students, key=get_name)
elif sort_index == 'g':
sorted_students = sorted(students, key=get_grade)
elif sort_index == 'a':
sorted_students = sorted(students, key=get_age)
else:
print('Unsupported option')
exit(1)
print(sorted_students)

最新更新