打印具有最大和的特定行数的 Python 程序


当需要打印具有最大和的特定数量行时,使用“排序”方法和“lambda”方法。

示例

以下是相同的演示

Open Compiler
my_list = [[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]] print("The list is :") print(my_list) my_key = 3 print("The key is") print(my_key) my_result = sorted(my_list, key=lambda row: sum(row), reverse=True)[:my_key] print("The resultant list is :") print(my_result)

输出

The list is :
[[2, 4, 6, 7], [2, 4, 8], [45], [1, 3, 5, 6], [8, 2, 1]]
The key is
3
The resultant list is :
[[45], [2, 4, 6, 7], [1, 3, 5, 6]]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个列表列表,并将其显示在控制台中。

  • 定义了一个键值,并将其显示在控制台中。

  • 在列表上使用“排序”方法以及 lambda 方法,其中元素的总和被确定,并且元素根据键值颠倒。

  • 这被指定给一个变量。

  • 这在控制台中显示为输出。

更新于:14-9-2021

162 次查看

开启你的 职业生涯

完成课程,获得认证

开始
广告