Python中方括号和括号括起来的列表有什么区别? [英] What's the difference between lists enclosed by square brackets and parentheses in Python?

查看:16
本文介绍了Python中方括号和括号括起来的列表有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> x=[1,2]
>>> x[1]
2
>>> x=(1,2)
>>> x[1]
2

它们都有效吗?出于某种原因是首选吗?

Are they both valid? Is one preferred for some reason?

推荐答案

方括号是 列表,而括号是元组.

Square brackets are lists while parentheses are tuples.

列表是可变的,这意味着您可以更改其内容:

A list is mutable, meaning you can change its contents:

>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]

虽然元组不是:

>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'

另一个主要区别是元组是可散列的,这意味着您可以将其用作字典的键等.例如:

The other main difference is that a tuple is hashable, meaning that you can use it as a key to a dictionary, among other things. For example:

>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

<小时>

请注意,正如许多人所指出的,您可以将元组添加在一起.例如:


Note that, as many people have pointed out, you can add tuples together. For example:

>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)

但是,这并不意味着元组是可变的.在上面的例子中,一个 new 元组是通过将两个元组加在一起作为参数来构造的.原始元组未修改.为了证明这一点,请考虑以下几点:

However, this does not mean tuples are mutable. In the example above, a new tuple is constructed by adding together the two tuples as arguments. The original tuple is not modified. To demonstrate this, consider the following:

>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)

然而,如果你用一个列表来构造这个相同的例子,y 也会被更新:

Whereas, if you were to construct this same example with a list, y would also be updated:

>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]

这篇关于Python中方括号和括号括起来的列表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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