gpt4 book ai didi

python - 在列表中制作按字母顺序排列的嵌套列表

转载 作者:行者123 更新时间:2023-11-28 17:56:18 25 4
gpt4 key购买 nike

我有一个任务,我需要按学生的姓氏将学生分类到嵌套列表中

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

最佳答案

您可以使用 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']]

关于python - 在列表中制作按字母顺序排列的嵌套列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58117784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com