我有一项任务,我需要按姓氏将学生分类到嵌套列表中
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])
我取消了该组的嵌套,并按字母顺序对其进行了排序,但是现在我不得不将它们放回嵌套列表中
因此,如果我的列表看起来像:new_group = ["James Allen", "Ricky Andrew", "Martin Brooks", "Andre Bryant"]
我可以将其转换为:[["James Allen", "Ricky Andrew"], ["Martin Brooks", "Andre Bryant"]]
答案 0 :(得分:1)
您可以使用itertools.groupby
生成嵌套:
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']]