Python中按子列表最大元素降序排序一组嵌套列表的实现问题
问题原因
你当前的代码没有为sorted()函数指定排序规则,默认会按照列表的字典序进行比较,而非你需要的「子列表最大元素」,这才导致排序结果不符合预期。
另外注意不要用list作为变量名,它是Python内置类型,重名会导致后续调用内置list功能时报错。
修改后代码
# 原始嵌套列表 nested_list = [[1, 2, 3], [5, 4, 3], [2, 0, 1], [2, 3, 4, 1]] # 指定排序key为每个子列表的最大值,开启reverse=True实现降序 output = sorted(nested_list, key=lambda sub: max(sub), reverse=True) for item in output: print(' '.join(str(e) for e in item))
运行输出
5 4 3 2 3 4 1 1 2 3 2 0 1
内容的提问来源于stack exchange,提问作者askemeline
相关产品推荐
相关产品推荐

