简体   繁体   中英

sorted() function on python for tuple

in this code, a tuple must be sorted but i ask a question of user that what kind of sort want, but the question asked four times:

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)

why ask question four times? terminal result

key=key_sort means that for each item key , the sorted() function will call key_sort(key) to determine the sorting order of that key. You have an input() in that function, and if there are 4 items in the list, that means key_sort() will have been called 4 times. It's just Python working as designed. If you want the input to not run every time, you have to use some kind of condition. Or, what would make more sense is to ask for the sorting method beforehand, and then set a class or global variable what_sort that key_sort then uses.

Ask first, then construct an appropriate function to pass to 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))

As @Joran Beasley pointed out, the key argument in sorted is called to every element in the iterable to be sorted (in your case, the variable students ).

A way to obtain the behavior you are asking is to modify the key_sort function to return another function which should be used as the key argument in your sorted call.

Please consider the following code

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)

That way, the user interaction (the input function call) will only run once.

The key parameter in the sorted function is the name of a function used to get the value to sort on. For example, in a list of integers, this is unnecessary because of course the objects themselves can directly be compared and sorted. But for tuples, it isn't clear how they should be compared. Using the first element? The last one? A hash of all of them? Python can't answer that question. key exists so you can specify how to do it.

The solution to your particular problem is to first ask the user the question, and then use their answer to choose how to sort the list. There's a lot of ways to do this, but here's how I think is the simplest.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM