📌  相关文章
📜  Python程序替换列表中除给定字符外的所有字符

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

Python程序替换列表中除给定字符外的所有字符

给定一个列表。任务是用 N 替换列表中除给定字符。

方法#1:使用列表理解+条件表达式

在此,我们使用列表推导执行迭代任务,并使用条件运算符处理替换。

Python3
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using list comprehension and conditional expressions
  
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing repl_chr
repl_chr = '$'
  
# initializing retain chararter
ret_chr = 'G'
  
# list comprehension to remake list after replacement
res = [ele if ele == ret_chr else repl_chr for ele in test_list]
  
# printing result
print("List after replacement : " + str(res))


Python3
# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using map() + lambda
  
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing repl_chr
repl_chr = '$'
  
# initializing retain chararter
ret_chr = 'G'
  
# using map() to extend logic to each element of list
res = list(map(lambda ele: ret_chr if ele == ret_chr else repl_chr, test_list))
  
# printing result
print("List after replacement : " + str(res))


输出
The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']

方法 #2:使用 map() + lambda

在此,我们使用 map() 和 lambda函数将逻辑扩展到列表的每个元素。

Python3

# Python3 code to demonstrate working of
# Replace all Characters Except K
# Using map() + lambda
  
# initializing lists
test_list = ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing repl_chr
repl_chr = '$'
  
# initializing retain chararter
ret_chr = 'G'
  
# using map() to extend logic to each element of list
res = list(map(lambda ele: ret_chr if ele == ret_chr else repl_chr, test_list))
  
# printing result
print("List after replacement : " + str(res))
输出
The original list : ['G', 'F', 'G', 'I', 'S', 'B', 'E', 'S', 'T']
List after replacement : ['G', '$', 'G', '$', '$', '$', '$', '$', '$']