Python – 将 K 分配给元组中的非 Max-Min 元素
有时,在处理Python数据时,我们可能会遇到需要根据特定条件分配特定值的问题。条件之一可以是非最大、最小元素。这类任务可能出现在日常编程和竞争性编程的许多应用中。让我们讨论可以执行此任务的某些方式。
Input :
test_tuple = (3, 6, 3, 6, 34, 34)
K = None
Output : (3, None, 3, None, 34, 34)
Input :
test_tuple = (3, 34)
K = None
Output : (3, 34)
方法 #1:使用max() + min() + tuple()
+ loop
上述功能的组合可以用来解决这个问题。在此,我们使用 min() 和 max() 执行查找最小和最大元素的任务,并蛮力将所有例外元素分配给 K。
# Python3 code to demonstrate working of
# Assign K to Non Max-Min elements in Tuple
# Using min() + max() + loop + tuple()
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing K
K = 4
# Assign K to Non Max-Min elements in Tuple
# Using min() + max() + loop + tuple()
res = []
for ele in test_tuple:
if ele not in [max(test_tuple), min(test_tuple)]:
res.append(K)
else:
res.append(ele)
res = tuple(res)
# printing result
print("The tuple after conversion: " + str(res))
输出 :
The original tuple : (5, 6, 3, 6, 10, 34)
The tuple after conversion: (4, 4, 3, 4, 4, 34)
方法 #2:使用生成器表达式 + max() + min() + tuple()
这是可以执行此任务的一种线性方法。在此,我们提取所有元素并使用生成器表达式分配适当的条件。
# Python3 code to demonstrate working of
# Assign K to Non Max-Min elements in Tuple
# Using generator expression + max() + min() + tuple()
# initializing tuple
test_tuple = (5, 6, 3, 6, 10, 34)
# printing original tuple
print("The original tuple : " + str(test_tuple))
# initializing K
K = 4
# Assign K to Non Max-Min elements in Tuple
# Using generator expression + max() + min() + tuple()
res = tuple(ele if ele in [min(test_tuple), max(test_tuple)] else K for ele in test_tuple)
# printing result
print("The tuple after conversion: " + str(res))
输出 :
The original tuple : (5, 6, 3, 6, 10, 34)
The tuple after conversion: (4, 4, 3, 4, 4, 34)