What#39;s the difference between lists enclosed by square brackets and parentheses in Python?(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中方括号和括号括起来的列表有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python中方括号和括号括起来的列表有什么区别?
基础教程推荐
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
