📌  相关文章
📜  Python – 替换大于 K 的元素

📅  最后修改于: 2022-05-13 01:55:32.753000             🧑  作者: Mango

Python – 替换大于 K 的元素

给定元素列表,用给定的替换字符替换所有大于 K 的元素。

方法#1:使用循环

在此,我们检查大于 K 的元素,如果找到,则将它们替换为 replace 字符,否则保留旧值。

Python3
# Python3 code to demonstrate working of 
# Replace Elements greater than K
# Using loop
  
# initializing list
test_list = [3, 4, 7, 5, 6, 7, 3, 4, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# initializing repl_chr 
repl_chr = "NA"
  
res = []
for ele in test_list:
      
    # replace if greater than K
    if ele > K :
        res.append(repl_chr)
    else :
        res.append(ele)
  
# printing result 
print("The replaced list : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Replace Elements greater than K
# Using list comprehension
  
# initializing list
test_list = [3, 4, 7, 5, 6, 7, 3, 4, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# initializing repl_chr 
repl_chr = "NA"
  
# one liner to solve problem
res = [repl_chr if ele > K else ele for ele in test_list]
  
# printing result 
print("The replaced list : " + str(res))


输出
The original list is : [3, 4, 7, 5, 6, 7, 3, 4, 6, 9]
The replaced list : [3, 4, 'NA', 5, 'NA', 'NA', 3, 4, 'NA', 'NA']

方法#2:使用列表推导

这是解决此问题的一种线性方法。与上面类似的方法,只使用一个衬垫。

Python3

# Python3 code to demonstrate working of 
# Replace Elements greater than K
# Using list comprehension
  
# initializing list
test_list = [3, 4, 7, 5, 6, 7, 3, 4, 6, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 5
  
# initializing repl_chr 
repl_chr = "NA"
  
# one liner to solve problem
res = [repl_chr if ele > K else ele for ele in test_list]
  
# printing result 
print("The replaced list : " + str(res))
输出
The original list is : [3, 4, 7, 5, 6, 7, 3, 4, 6, 9]
The replaced list : [3, 4, 'NA', 5, 'NA', 'NA', 3, 4, 'NA', 'NA']