Python – 用 K 替换 Non-None
有时,在使用Python列表时,我们可能会遇到需要替换所有非无元素的问题。这类问题可以在许多领域都有应用,例如 Web 开发和日常编程。让我们讨论可以执行此任务的某些方式。
Input : test_list = [2, None, None, 5, ”], K = 9
Output : [9, None, None, 9, ”]
Input : test_list = [”, None], K = 10
Output : [”, None]
方法#1:使用列表推导
这是可以执行此任务的方式之一。在此,我们使用条件执行遍历和替换内部理解的任务。
Python3
# Python3 code to demonstrate working of
# Replace Non-None with K
# Using list comprehension
# initializing list
test_list = [59, 236, None, 3, '']
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 'Gfg'
# Replace Non-None with K
# Using list comprehension
res = [K if ele else ele for ele in test_list]
# printing result
print("List after replacement : " + str(res))
Python3
# Python3 code to demonstrate working of
# Replace Non-None with K
# Using map() + lambda()
# initializing list
test_list = [59, 236, None, 3, '']
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 'Gfg'
# Replace Non-None with K
# Using map() + lambda()
res = list(map(lambda ele: K if ele else ele, test_list))
# printing result
print("List after replacement : " + str(res))
输出 :
The original list : [59, 236, None, 3, '']
List after replacement : ['Gfg', 'Gfg', None, 'Gfg', '']
方法 #2:使用map() + lambda()
上述功能的组合可以用来解决这个问题。在此,我们使用 map() 执行将 lambda 逻辑扩展到整个列表的任务并执行替换。
Python3
# Python3 code to demonstrate working of
# Replace Non-None with K
# Using map() + lambda()
# initializing list
test_list = [59, 236, None, 3, '']
# printing original list
print("The original list : " + str(test_list))
# initializing K
K = 'Gfg'
# Replace Non-None with K
# Using map() + lambda()
res = list(map(lambda ele: K if ele else ele, test_list))
# printing result
print("List after replacement : " + str(res))
输出 :
The original list : [59, 236, None, 3, '']
List after replacement : ['Gfg', 'Gfg', None, 'Gfg', '']