Python程序根据与数字的比较替换列表的元素
给定一个列表,这里的任务是编写一个Python程序,将其元素与此处使用 K 描述的另一个数字进行比较后替换其元素。
对于本文中描述的示例,任何大于 K 的数字都将替换为 high 中给定的值,任何小于或等于 K 的数字都将替换为 low 中给出的值。
Input : test_list = [7, 4, 3, 2, 6, 8, 9, 1], low = 2, high = 9, K = 5
Output : [9, 2, 2, 2, 9, 9, 9, 2]
Explanation : Elements less than K substituted by 2, rest are by 9.
Input : test_list = [7, 4, 3, 2, 6, 8, 9, 1], low =2, high = 8, K = 5
Output : [8, 2, 2, 2, 8, 8, 8, 2]
Explanation : Elements less than K substituted by 2, rest are by 8.
方法一:使用循环
在这里,我们使用条件语句执行替换,并使用循环执行迭代。
程序:
Python3
# initializing list
test_list = [7, 4, 3, 2, 6, 8, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# initializing low and high Replacement Replacement
low, high = 2, 9
res = []
for ele in test_list:
# conditional tests
if ele > K:
res.append(high)
else:
res.append(low)
# printing result
print("List after replacement ? : " + str(res))
Python3
# initializing list
test_list = [7, 4, 3, 2, 6, 8, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# initializing low and high Replacement Replacement
low, high = 2, 9
# list comprehension for shorthand solution
res = [high if ele > K else low for ele in test_list]
# printing result
print("List after replacement ? : " + str(res))
输出:
The original list is : [7, 4, 3, 2, 6, 8, 9, 1]
List after replacement ? : [9, 2, 2, 2, 9, 9, 9, 2]
方法 2:使用列表理解
与上面的方法类似,唯一的区别是这是一个单一的线性解决方案和一个使用列表理解的紧凑替代方案。
程序:
蟒蛇3
# initializing list
test_list = [7, 4, 3, 2, 6, 8, 9, 1]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 5
# initializing low and high Replacement Replacement
low, high = 2, 9
# list comprehension for shorthand solution
res = [high if ele > K else low for ele in test_list]
# printing result
print("List after replacement ? : " + str(res))
输出:
The original list is : [7, 4, 3, 2, 6, 8, 9, 1]
List after replacement ? : [9, 2, 2, 2, 9, 9, 9, 2]