在lis中创建按字母顺序排列的嵌套列表

2024-05-19 12:51:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个任务,我需要把学生按姓氏排列成嵌套列表

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"]]


Tags: in列表newforgroupgroupsmartinpupil
1条回答
网友
1楼 · 发布于 2024-05-19 12:51:39

可以使用^{}生成嵌套:

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']]

相关问题 更多 >