Luca Marinescu
Luca Marinescu

Reputation: 43

Making alphabetised nested lists inside a list

I have a task where i need to sort students into nested lists by their last names

new_group=[] # new, unnested group
for x in groups:
    for pupil in x:
        new_group.append(pupil)  #this adds every student to the unnested group

def sort(groups):
    new_group= sorted(new_group, key= lambda x: x.split(" ")[1])

I un-nested the group and sorted them alphabetically but now I have to put them back into nested lists so if my list looks like: new_group = ["James Allen", "Ricky Andrew", "Martin Brooks", "Andre Bryant"] I can turn it into: [["James Allen", "Ricky Andrew"], ["Martin Brooks", "Andre Bryant"]]

Upvotes: 3

Views: 84

Answers (1)

tzaman
tzaman

Reputation: 47830

You can use itertools.groupby to produce your nesting:

from itertools import groupby

def last_name(name):
    return name.split()[-1] # Also works for middle names

def last_initial(name):
    return last_name(name)[0] # First letter of last name

groups = [['Martin Brooks'], ['Ricky Andrew'], ['Andre Bryant'], ['James Allen']]
sorted_pupils = sorted((pupil for g in groups for pupil in g), key=last_name)
grouped_pupils = [list(g) for _, g in groupby(sorted_pupils, key=last_initial)]
print(grouped_pupils)
# Produces [['James Allen', 'Ricky Andrew'], ['Martin Brooks', 'Andre Bryant']]

Upvotes: 1

Related Questions