Python - 自定义下界列表
给定一个列表,为其分配一个自定义下限值。
Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 3
Output : [5, 7, 8, 3, 3, 5, 3]
Explanation : All elements less than 3, assigned 3.
Input : test_list = [5, 7, 8, 2, 3, 5, 1], K = 5
Output : [5, 7, 8, 5, 5, 5, 5]
Explanation : All elements less than 5, assigned 5.
方法#1:使用列表理解
在这里,我们检查每个元素是否低于下限,如果是,则将决定的下限分配给该元素。
Python3
# Python3 code to demonstrate working of
# Custom Lowerbound a List
# Using list comprehension
# initializing list
test_list = [5, 7, 8, 2, 3, 5, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing Lowerbound
K = 4
# checking for elements and assigning Lowerbounds
res = [ele if ele >= K else K for ele in test_list]
# printing result
print("List with Lowerbounds : " + str(res))
Python3
# Python3 code to demonstrate working of
# Custom Lowerbound a List
# Using list comprehension + max()
# initializing list
test_list = [5, 7, 8, 2, 3, 5, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing Lowerbound
K = 4
# max() is used to compare for Lowerbound
res = [max(ele, K) for ele in test_list]
# printing result
print("List with Lowerbounds : " + str(res))
输出
The original list is : [5, 7, 8, 2, 3, 5, 1]
List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]
方法 #2:使用列表理解 + max()
在这种情况下,我们使用 max() 进行比较,分配元素的最大值或决定的下限。
蟒蛇3
# Python3 code to demonstrate working of
# Custom Lowerbound a List
# Using list comprehension + max()
# initializing list
test_list = [5, 7, 8, 2, 3, 5, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing Lowerbound
K = 4
# max() is used to compare for Lowerbound
res = [max(ele, K) for ele in test_list]
# printing result
print("List with Lowerbounds : " + str(res))
输出
The original list is : [5, 7, 8, 2, 3, 5, 1]
List with Lowerbounds : [5, 7, 8, 4, 4, 5, 4]