Python|根据第 N 个元组元素替换元组
有时,在处理数据时,我们可能会遇到需要替换与特定数据条目匹配的条目的问题。这可以是匹配的电话号码、ID 等。这在 Web 开发领域有它的应用。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + enumerate()
可以使用循环和枚举函数的组合来执行此任务,这有助于访问第 N 个元素,然后在满足条件时检查和替换。
# Python3 code to demonstrate working of
# Replace tuple according to Nth tuple element
# Using loops + enumerate()
# Initializing list
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing change record
repl_rec = ('is', 2)
# Initializing N
N = 1
# Replace tuple according to Nth tuple element
# Using loops + enumerate()
for key, val in enumerate(test_list):
if val[N] == repl_rec[N]:
test_list[key] = repl_rec
break
# printing result
print("The tuple after replacement is : " + str(test_list))
输出 :
The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]
方法#2:使用列表推导
这是解决此特定问题的单线方法。在此,我们只是迭代列表元素并保持匹配匹配的元组第 N 个元素并执行替换。
# Python3 code to demonstrate working of
# Replace tuple according to Nth tuple element
# Using list comprehension
# Initializing list
test_list = [('gfg', 1), ('was', 2), ('best', 3)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing change record
repl_rec = ('is', 2)
# Initializing N
N = 1
# Replace tuple according to Nth tuple element
# Using list comprehension
res = [repl_rec if sub[N] == repl_rec[N] else sub for sub in test_list]
# printing result
print("The tuple after replacement is : " + str(res))
输出 :
The original list is : [('gfg', 1), ('was', 2), ('best', 3)]
The tuple after replacement is : [('gfg', 1), ('is', 2), ('best', 3)]