Python|修改相等的元组行
有时,在使用Python Records 时,我们可能会遇到一个问题,即我们需要在记录的相等性上执行元素记录的修改。这在涉及数据的域中可能会出现问题。让我们讨论可以执行此任务的某些方式。
Input :
test_list = [[(12, 5)], [(13, 2)], [(6, 7)]]
test_row = [(13, 2)]
Output : [[(12, 5)], [(13, 8)], [(6, 7)]]
Input :
test_list = [[(12, 5), (7, 6)]]
test_row = [(13, 2)]
Output : [[(12, 5), (7, 6)]]
方法 #1:使用循环 + enumerate()
上述功能的组合可以用来解决这个问题。在此,我们使用蛮力来执行检查相等性和执行所需修改的任务。
# Python3 code to demonstrate working of
# Modify Equal Tuple Rows
# Using loop + enumerate()
# initializing list
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check row
test_row = [(12, 2), (13, 2)]
# Modify Equal Tuple Rows
# Using loop + enumerate()
# multiple y coordinate by 4
for idx, val in enumerate(test_list):
if val == test_row:
temp = []
for sub in val:
ele = (sub[0], sub[1] * 4)
temp.append(ele)
test_list[idx] = temp
# printing result
print("List after modification : " + str(test_list))
输出 :
The original list is : [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
List after modification : [[(12, 5), (13, 6)], [(12, 8), (13, 8)]]
方法#2:使用列表推导
这是可以执行此任务的另一种方式。在此,我们使用列表推导以类似于上述方法的单线方式执行任务。
# Python3 code to demonstrate working of
# Modify Equal Tuple Rows
# Using list comprehension
# initializing list
test_list = [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
# printing original list
print("The original list is : " + str(test_list))
# initializing check row
test_row = [(12, 2), (13, 2)]
# Modify Equal Tuple Rows
# Using list comprehension
# multiple y coordinate by 4
res = [[(sub[0], sub[1] * 4) for sub in ele] if ele == test_row else ele for ele in test_list]
# printing result
print("List after modification : " + str(res))
输出 :
The original list is : [[(12, 5), (13, 6)], [(12, 2), (13, 2)]]
List after modification : [[(12, 5), (13, 6)], [(12, 8), (13, 8)]]