user2436815
user2436815

Reputation: 3915

Python: Sorting List of Lists by a String Element

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?)

Upvotes: 0

Views: 103

Answers (2)

Paulo Bu
Paulo Bu

Reputation: 29804

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.

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304473

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)

Upvotes: 2

Related Questions