如果在Python中我将一个列表放在一个元组中,是否可以安全地更改该列表的内容? [英] If in Python I put a list inside a tuple, can I safely change the contents of that list?

查看:100
本文介绍了如果在Python中我将一个列表放在一个元组中,是否可以安全地更改该列表的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

元组中的值只是对列表的引用,如果我更改列表中的值,那么一切仍然井井有条,对吗?我想确保,如果这样做,我不会开始遇到令人困惑的错误.

The value inside the tuple is simply a reference to a list, and if I change the values in the list everything is still in order, right? I want to make sure that if I do this I won't start running into confusing errors.

推荐答案

Tuples是不可变的,您不能更改其内容.

Tuples are immutable, you may not change their contents.

带有列表

>>> x = [1,2,3]
>>> x[0] = 5
>>> x
[5, 2, 3]

带有元组

>>> y = tuple([1,2,3])
>>> y
(1, 2, 3)
>>> y[0] = 5   # Not allowed!

Traceback (most recent call last):
  File "<pyshell#20>", line 1, in <module>
    y[0] = 5
TypeError: 'tuple' object does not support item assignment

但是,如果我理解您的问题,请说您已经

But if I understand your question, say you have

>>> a = [1,2,3]
>>> b = [4,5,6]
>>> t = (a,b)
>>> t
([1, 2, 3], [4, 5, 6])

被允许将内部列表修改为

>>> t[0][0] = 5
>>> t
([5, 2, 3], [4, 5, 6])

这篇关于如果在Python中我将一个列表放在一个元组中,是否可以安全地更改该列表的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆