以下是一个修改包含元组的列表的Python函数的示例代码:
def modify_tuple_list(lst, index, new_value):
for i in range(len(lst)):
if index < len(lst[i]):
lst[i] = lst[i][:index] + (new_value,) + lst[i][index+1:]
return lst
# 示例用法
tuple_list = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
index = 1
new_value = 10
modified_list = modify_tuple_list(tuple_list, index, new_value)
print(modified_list)
这个函数接受一个包含元组的列表 lst
,以及要修改的元组的索引 index
和新值 new_value
。它使用一个循环遍历列表中的每个元组。然后,它检查给定索引是否在元组的范围内,如果是,则替换元组中指定索引位置的元素为新值,返回修改后的列表。
在示例中,我们传递一个包含三个元组的列表 [(1, 2, 3), (4, 5, 6), (7, 8, 9)]
,要修改的索引为1,新值为10。函数修改了索引为1的元组中的第二个元素,并返回修改后的列表。输出结果为[(1, 10, 3), (4, 10, 6), (7, 10, 9)]
。