📜  Python - 编辑元组内的对象

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

Python - 编辑元组内的对象

有时,在使用元组时,由于是不可变的,可能会对其工作产生很多混淆。可以从脑海中浮现的问题之一是,元组中的对象是可变的吗?答案是肯定的。让我们讨论一些可以实现这一目标的方法。

方法#1:使用访问方法
这是可以执行元组对象内部编辑的方式之一。这与任何其他容器类似,并使用列表访问方法就地发生。

# Python3 code to demonstrate working of 
# Edit objects inside tuple
# Using Access Methods
  
# initializing tuple
test_tuple = (1, [5, 6, 4], 9, 10)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Edit objects inside tuple
# Using Access Methods
test_tuple[1][2] = 14
         
# printing result 
print("The modified tuple : " + str(test_tuple)) 
输出 :
The original tuple : (1, [5, 6, 4], 9, 10)
The modified tuple : (1, [5, 6, 14], 9, 10)

方法 #2:使用pop() + index()
上述功能的组合也可以用来解决这个问题。在此,我们使用 pop() 执行删除任务,并使用 index() 在特定索引处添加元素。

# Python3 code to demonstrate working of 
# Edit objects inside tuple
# Using pop() + index()
  
# initializing tuple
test_tuple = (1, [5, 6, 4], 9, 10)
  
# printing original tuple
print("The original tuple : " + str(test_tuple))
  
# Edit objects inside tuple
# Using pop() + index()
test_tuple[1].pop(2)
test_tuple[1].insert(2, 14)      
  
# printing result 
print("The modified tuple : " + str(test_tuple)) 
输出 :
The original tuple : (1, [5, 6, 4], 9, 10)
The modified tuple : (1, [5, 6, 14], 9, 10)