简体   繁体   中英

Sorting 2D arrays in fuction in Python 2.7

So! Hi everybody. I hope you'll help me figure this one out. I need to write a function with the signature sort_2D_List( List ) → List, which should sort the students in my 2D list by name. I came up with this code:

comp_sci_students = [ ['Steve Jobs', 0, 'G40F'] , ['Ada Lovelace', 1, 'G400'], ['Virginia Woolf', 2, 'G300'] ]

def sort_2D_List(List):
    return List

List = comp_sci_students
List.sort(key=lambda x:x[0], reverse=False)

sort_2D_List(List)

But it would not give me any output. Could you explain what is wrong?

Thanks in advance

You have a lot of things going on here that probably are not what you think

  1. Your list is "comp_sci_students" you don't need to reassign it to a different variable

  2. You are currently attempting your sort as a Lambda function, presumably that should happen in your function

  3. Your function currently is not doing anything. You give it a list and all it does is return that same list

  4. Since your function is returning something (a list) You need to receive that return somehow. Something like new_list = sort_2D_List(list)

What you presumably are trying to do is:

comp_sci_students = [ ['Steve Jobs', 0, 'G40F'] , ['Ada Lovelace', 1, 'G400'], ['Virginia Woolf', 2, 'G300'] ]

def sort_2D_List(input_list):
    input_list.sort(key=lambda x:x[0], reverse=False)
    return input_list

output_list = sort_2D_List(comp_sci_students)
# Do something with the output List (Print?)

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