我创建了一个三维数组,用于存储保龄球队的信息。我把它组织在我的头脑中作为一个目录,其中包含团队,这些团队中有个人资料,个人资料包括玩家姓名,团队编号和分数。
我创建了一个使用的测试列表:
test = [
[["John",1,153],["Lizzy",1,129],["Matt",1,178]],
[["Jorge",2,156],["Brent",2,145],["Kyle",2,207]],
[["Chuck",3,300]],
[["Joey",4,230],["Stanley",4,60]]
]
我想按照其分数创建所有配置文件的排序列表,并按字母顺序按名称创建另一个列表。我可以用for循环做这个,但是使用sorted()
看起来会好很多。有没有办法在sorted()
函数中使用key参数来执行此操作?
这就是我最终做的事情
def sort_score(directory):
sorted_score = []
for team in directory:
for profile in team:
sorted_score.append(profile)
sorted_score = sorted(sorted_score,key=takeScore,reverse=True)
return sorted_score
def takeScore(elem):
return elem[2]
你想做两件事:flatten the list和sort the result by a specific index。
from operator import itemgetter
test = [
[["John",1,153],["Lizzy",1,129],["Matt",1,178]],
[["Jorge",2,156],["Brent",2,145],["Kyle",2,207]],
[["Chuck",3,300]],
[["Joey",4,230],["Stanley",4,60]]
]
sorted_by_name = sorted([p for team in test for p in team], key=itemgetter(0))
sorted_by_score = sorted([p for team in test for p in team], key=itemgetter(2))