📜  Python – 用第 K 个字典值替换字符串

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

Python – 用第 K 个字典值替换字符串

给定字符串列表,将映射的值替换为映射列表的第 K 个值。

方法#1:使用列表推导

这是可以执行此任务的方式之一。在此,我们在列表理解的单行内执行任务迭代和条件替换。

Python3
# Python3 code to demonstrate working of 
# Replace String by Kth Dictionary value  
# Using list comprehension
  
# initializing list
test_list = ["Gfg", "is", "Best"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing subs. Dictionary
subs_dict = {
    "Gfg" : [5, 6, 7], 
    "is" : [7, 4, 2], 
}
  
# initializing K 
K = 2
  
# using list comprehension to solve
# problem using one liner
res = [ele if ele not in subs_dict else subs_dict[ele][K]
                                     for ele in test_list]
          
# printing result 
print("The list after substitution : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Replace String by Kth Dictionary value  
# Using get() + list comprehension
  
# initializing list
test_list = ["Gfg", "is", "Best"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing subs. Dictionary
subs_dict = {
    "Gfg" : [5, 6, 7], 
    "is" : [7, 4, 2], 
}
  
# initializing K 
K = 2
  
# using list comprehension to solve problem using one liner
# get() to perform presence checks and assign default value
res = [subs_dict.get(ele, ele) for ele in test_list]
res = [ele[K] if isinstance(ele, list) else ele for ele in res] 
          
# printing result 
print("The list after substitution : " + str(res))


输出
The original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']

方法 #2:使用 get() + 列表推导

上述功能的组合可以用来解决这个问题。在此,我们使用列表推导进行迭代,并使用 get() 检查键是否存在和替换。

Python3

# Python3 code to demonstrate working of 
# Replace String by Kth Dictionary value  
# Using get() + list comprehension
  
# initializing list
test_list = ["Gfg", "is", "Best"]
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing subs. Dictionary
subs_dict = {
    "Gfg" : [5, 6, 7], 
    "is" : [7, 4, 2], 
}
  
# initializing K 
K = 2
  
# using list comprehension to solve problem using one liner
# get() to perform presence checks and assign default value
res = [subs_dict.get(ele, ele) for ele in test_list]
res = [ele[K] if isinstance(ele, list) else ele for ele in res] 
          
# printing result 
print("The list after substitution : " + str(res))
输出
The original list : ['Gfg', 'is', 'Best']
The list after substitution : [7, 2, 'Best']