Python – 元组中的最大和最小 K 个元素
有时,在处理元组时,我们可能会遇到只需要提取极端K 个元素的问题,即Tuple 中的最大和最小K 个元素。这个问题可以有跨领域的应用,例如 Web 开发和数据科学。让我们讨论一些可以解决这个问题的方法。
Input : test_tup = (3, 7, 1, 18, 9), k = 2
Output : (3, 1, 9, 18)
Input : test_tup = (3, 7, 1), k=1
Output : (1, 3)
方法 #1:使用 sorted() + 循环
上述功能的组合可以用来解决这个问题。在此,我们使用 sorted() 执行排序操作,以及使用循环提取最大和最小 K 个元素的问题。
Python3
# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using sorted() + loop
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# initializing K
K = 2
# Maximum and Minimum K elements in Tuple
# Using sorted() + loop
res = []
test_tup = list(sorted(test_tup))
for idx, val in enumerate(test_tup):
if idx < K or idx >= len(test_tup) - K:
res.append(val)
res = tuple(res)
# printing result
print("The extracted values : " + str(res))
Python3
# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using slicing + sorted()
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# initializing K
K = 2
# Maximum and Minimum K elements in Tuple
# Using slicing + sorted()
test_tup = list(test_tup)
temp = sorted(test_tup)
res = tuple(temp[:K] + temp[-K:])
# printing result
print("The extracted values : " + str(res))
输出 :
The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)
方法 #2:使用列表切片 + sorted()
上述功能的组合可以用来解决这个问题。在此,我们使用切片而不是蛮力循环逻辑执行最大、最小提取任务。
Python3
# Python3 code to demonstrate working of
# Maximum and Minimum K elements in Tuple
# Using slicing + sorted()
# initializing tuple
test_tup = (5, 20, 3, 7, 6, 8)
# printing original tuple
print("The original tuple is : " + str(test_tup))
# initializing K
K = 2
# Maximum and Minimum K elements in Tuple
# Using slicing + sorted()
test_tup = list(test_tup)
temp = sorted(test_tup)
res = tuple(temp[:K] + temp[-K:])
# printing result
print("The extracted values : " + str(res))
输出 :
The original tuple is : (5, 20, 3, 7, 6, 8)
The extracted values : (3, 5, 8, 20)