python 怎么申请“可变”元组

元组申请后不可改变

元组不可变的是元组元素指向的地址,不是地址中的值,如果元组指向list地址时,list内的值是可以改变的。

例子如下:

test = ([1],[2])
test[0][0] = 8
test
([8], [2])

用乘以个数得到的元组,指向同一个地址,改地址list内值的改变会引起元祖中所有list值的改变,如下:

t = ([0],)*5
w = {w:{'统计树':t, 'ind':ind} for ind,w in enumerate(['a','b','c'])}
w
{'a': {'统计树': ([0], [0], [0], [0], [0]), 'ind': 0},
 'b': {'统计树': ([0], [0], [0], [0], [0]), 'ind': 1},
 'c': {'统计树': ([0], [0], [0], [0], [0]), 'ind': 2}}
w['a']['统计树'][0][0] = 3
w
{'a': {'统计树': ([3], [3], [3], [3], [3]), 'ind': 0},
 'b': {'统计树': ([3], [3], [3], [3], [3]), 'ind': 1},
 'c': {'统计树': ([3], [3], [3], [3], [3]), 'ind': 2}}

如何新建包含list的元祖同时,指向不同的list地址(改变其中一个值,不影响其它值)

新建包含list的元祖,可以先生成list,再转为元祖,如下:

test2 = [[i] for i in range(5)]
test2
[[0], [1], [2], [3], [4]]
tuple(test2)
([0], [1], [2], [3], [4])
test2[2][0] = 9
test2
[[0], [1], [9], [3], [4]]

你可能感兴趣的:(程序积累)