📜  Python|将 N 添加到第 K 个元组元素

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

Python|将 N 添加到第 K 个元组元素

很多时候,在处理记录时,我们可能会遇到需要更改元组元素值的问题。这是使用元组时的常见问题。让我们讨论一下可以将 N 添加到列表中元组的第 K 个元素的某些方法。

方法#1:使用循环
使用循环可以执行此任务。在此,我们只是迭代列表以通过代码中的预定义值 N 更改第 K 个元素。

# Python3 code to demonstrate working of
# Adding N to Kth tuple element
# 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 = 3 
  
# Initializing K 
K = 1
  
# Adding N to Kth tuple element
# Using loop
res = []
for i in range(0, len(test_list)):
    res.append((test_list[i][0], test_list[i][K] + N, test_list[i][2]))
  
# printing result
print("The tuple after adding N to Kth element : " + str(res))
输出 :
The original list is : [(4, 5, 6), (7, 4, 2), (9, 10, 11)]
The tuple after adding N to Kth element : [(4, 8, 6), (7, 7, 2), (9, 13, 11)]

方法#2:使用列表推导
此方法与上述方法具有相同的方法,只是使用列表理解功能减少了代码行,以使代码按大小紧凑。

# Python3 code to demonstrate working of
# Adding N to Kth tuple element
# 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 = 3 
  
# Initializing K 
K = 1
  
# Adding N to Kth tuple element
# Using list comprehension
res = [(a, b + N, c) for a, b, c in test_list]
  
# printing result
print("The tuple after adding N to Kth element : " + str(res))
输出 :
The original list is : [(4, 5, 6), (7, 4, 2), (9, 10, 11)]
The tuple after adding N to Kth element : [(4, 8, 6), (7, 7, 2), (9, 13, 11)]