0

Lets say I have the following Python list:

mylist = [
    ["name_a", "sex_male", "age_15", "grade_11"],
    ["name_b", "sex_male", "age_18", "grade_9"],
    ["name_c", "sex_male", "age_11", "grade_8"],
    ["name_d", "sex_male", "age_16", "grade_12"],
    ["name_e", "sex_male", "age_19", "grade_13"],
]

I want to call Python's sort() function to sort mylist by age

For instance, I want to do something like this:

mylist.sort(key=...)

to get the output

mylist = [
    ["name_c", "sex_male", "age_11", "grade_8"],
    ["name_a", "sex_male", "age_15", "grade_11"],
    ["name_d", "sex_male", "age_16", "grade_12"],
    ["name_b", "sex_male", "age_18", "grade_9"],
    ["name_e", "sex_male", "age_19", "grade_13"],
]

What is the right way to do this?

P.S

One more question: why sorting algorithm is used in Python's sort() function? (ex. QuickSort?)

2
  • possible duplicate of In Python how do I sort a list of dictionaries by values of the dictionary? Commented Mar 29, 2014 at 22:12
  • write a function to extract the age from one item. Use that as the key function. This is preferable to using a lambda for anything more than simple cases, because that way you can write unittests for that function. Commented Mar 29, 2014 at 22:16

2 Answers 2

3
def extract_age(item):
    """age is stored in the 3rd element of item. eg.
      ['name_c', 'sex_male', 'age_11', 'grade_8']
      and should be returned as an int
    """
    return int(item[2].split('_')[1])

mylist.sort(key=extract_age)
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Although probably the lambda is more pythonic, A Foolish Consistency is the Hobgoblin of Little Minds and the age extracting function is very worthwhile testing it. Why don't you include your comment in the answer? Is a good motivation.
1

Assuming all ages look the same you can do:

>>>mylist.sort(key=lambda e: int(e[2].split('_')[1]))
[['name_c', 'sex_male', 'age_11', 'grade_8'],
 ['name_a', 'sex_male', 'age_15', 'grade_11'],
 ['name_d', 'sex_male', 'age_16', 'grade_12'],
 ['name_b', 'sex_male', 'age_18', 'grade_9'],
 ['name_e', 'sex_male', 'age_19', 'grade_13']]

The lambda expressions just parses the age field by splitting the string on the _ character and converting to int the result of the split's second element.

Python uses TimSort algorithm, a tailored search algorithm for Python created by Tim Peters.

2 Comments

Note that OP wants to use mylist.sort(key=...)
@Christian right, I'm just used to sorted, I'll edit, thanks :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.