Python – 常数乘法到第 N 列
很多时候,在处理记录时,我们可能会遇到需要更改元组元素值的问题。这是使用元组时的常见问题。让我们讨论一些可以将 K 乘以列表中元组的第 N 个元素的方法。
方法#1:使用循环
使用循环可以执行此任务。在此,我们只是迭代列表以通过代码中预定义的值 K 更改第 N 个元素。
# Python3 code to demonstrate working of
# Constant Multiplication to Nth Column
# Using loop
# Initializing list
test_list = [(4, 5, 6), (7, 4, 2), (9, 10, 11)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing N
N = 1
# Initializing K
K = 3
# Constant Multiplication to Nth Column
# Using loop
res = []
for i in range(0, len(test_list)):
res.append((test_list[i][0], test_list[i][N] * K, test_list[i][2]))
# printing result
print("The tuple after multiplying K to Nth element : " + str(res))
输出 :
The original list is : [(4, 5, 6), (7, 4, 2), (9, 10, 11)]
The tuple after multiplying K to Nth element : [(4, 15, 6), (7, 12, 2), (9, 30, 11)]
方法#2:使用列表推导
此方法与上述方法具有相同的方法,只是使用列表理解功能减少代码行数,以使代码按大小紧凑。
# Python3 code to demonstrate working of
# Constant Multiplication to Nth Column
# Using list comprehension
# Initializing list
test_list = [(4, 5, 6), (7, 4, 2), (9, 10, 11)]
# printing original list
print("The original list is : " + str(test_list))
# Initializing N
N = 1
# Initializing K
K = 3
# Constant Multiplication to Nth Column
# Using list comprehension
res = [(a, b * K, c) for a, b, c in test_list]
# printing result
print("The tuple after multiplying K to Nth element : " + str(res))
输出 :
The original list is : [(4, 5, 6), (7, 4, 2), (9, 10, 11)]
The tuple after multiplying K to Nth element : [(4, 15, 6), (7, 12, 2), (9, 30, 11)]