使用 Python 在元组中找出最大和最小 K 元素
当需要在元组中找出最大和最小 K 元素时,可以使用“sorted”方法对元素进行排序,然后枚举它们,最后获取第一个和最后一个元素。
以下是相同代码的演示:
示例
my_tuple = (7, 25, 36, 9, 6, 8)
print("The tuple is : ")
print(my_tuple)
K = 2
print("The value of K has been initialized to ")
print(K)
my_result = []
my_tuple = list(my_tuple)
temp = sorted(my_tuple)
for idx, val in enumerate(temp):
if idx < K or idx >= len(temp) - K:
my_result.append(val)
my_result = tuple(my_result)
print("The result is : " )
print(my_result)输出
The tuple is : (7, 25, 36, 9, 6, 8) The value of K has been initialized to 2 The result is : (6, 7, 25, 36)
解释
定义元组,并显示在控制台上。
定义 K 的值。
定义一个空列表。
元组转换为列表。
对其进行排序并存储在变量中。
对其进行迭代,如果小于 K 或大于列表长度和 K 之间的差,则将其附加到空列表。
这是显示在控制台上的输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP