如何按points、wins及球队名称对含字典的嵌套列表多条件排序?
问题分析与解决方案
原代码存在的问题
- 排序键错误:你在
sorted中使用了整个国家名列表j作为第三个排序键,这个值对所有字典元素完全相同,导致排序无法区分元素,自然没有效果。 - 未正确提取国家名:没有从每个字典中单独取出对应的国家名,无法基于球队名称进行排序。
- Reverse参数使用不当:
reverse=True会反转所有排序维度,但你需要前两个条件(points、wins)降序,第三个条件(国家名)升序,直接用reverse会让国家名也按降序排列,不符合需求。
正确实现代码
我们先定义一个辅助函数提取每个字典中的国家名,再通过调整排序键实现需求:
all_dicts_lst = [ { "Spain": 0, "wins": 0, "loses": 0, "draws": 3, "goal difference": 0, "points": 3 }, { "Iran": 0, "wins": 0, "loses": 0, "draws": 3, "goal difference": 0, "points": 3 }, { "Portugal": 0, "wins": 0, "loses": 0, "draws": 3, "goal difference": 0, "points": 3, }, { "Morraco": 0, "wins": 0, "loses": 0, "draws": 3, "goal difference": 0, "points": 3, }, ] # 提取字典中的国家名(排除固定属性键) def get_country(d): for key in d: if key not in ["wins", "loses", "draws", "goal difference", "points"]: return key # 核心排序逻辑: # - 对points和wins取负数,实现降序排序 # - 国家名转小写后按字母升序排序 sorted_all_dics = sorted( all_dicts_lst, key=lambda x: (-x["points"], -x["wins"], get_country(x).lower()) ) # 打印结果 for team in sorted_all_dics: country = get_country(team) print(f"{country} wins:{team['wins']} , loses:{team['loses']} , draws:{team['draws']} , goal difference:{team['goal difference']} , points:{team['points']}")
输出结果
运行后会得到按points降序、wins降序,且同分时国家名字母升序的结果:
Iran wins:0 , loses:0 , draws:3 , goal difference:0 , points:3 Morraco wins:0 , loses:0 , draws:3 , goal difference:0 , points:3 Portugal wins:0 , loses:0 , draws:3 , goal difference:0 , points:3 Spain wins:0 , loses:0 , draws:3 , goal difference:0 , points:3
可选方案(使用reverse=True)
如果一定要用reverse=True,可以将国家名转换为反向字符串,让reverse后的排序效果等价于原字符串的升序:
sorted_all_dics = sorted( all_dicts_lst, key=lambda x: (x["points"], x["wins"], get_country(x).lower()[::-1]), reverse=True )
内容的提问来源于stack exchange,提问作者aszx 6309
相关产品推荐
相关产品推荐

