python - 元组和列表的不同访问元素

标签 python list tuples

为什么在将 t 设为 tuple 时,在访问 t 的元素时存在这种差异?

>>> t = [('ID','int')]
>>> for r in t:
print r


('ID', 'int')


t = (('ID','int'))
>>> for r in t:
print r


ID
int

我希望这与第一个示例完全相同!而用多个元素填充元组时,行为会发生变化。

>>> t = (('ID','int'),('DEF','str'))
>>> for r in t:
print r


('ID', 'int')
('DEF', 'str')
>>> t = [('ID','int'),('DEF','str')]
>>> for r in t:
print r


('ID', 'int')
('DEF', 'str')

谁能给个简短的解释?我正在运行 python 2.7

最佳答案

(('a', 'b'))('a', 'b') 相同。

你实际上想要 (('a', 'b'),)

这在此处记录:

5.13. Expression lists

expression_list ::= expression ( "," expression )* [","]

An expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.

The trailing comma is required only to create a single tuple (a.k.a. a singleton); it is optional in all other cases. A single expression without a trailing comma doesn’t create a tuple, but rather yields the value of that expression. (To create an empty tuple, use an empty pair of parentheses: ().)

请记住,如果没有此限制,表达式 (3) * (4) 应该是两个数字或两个元组的乘积吗?大多数用户会期望它是数字的乘法。

关于python - 元组和列表的不同访问元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12496435/

相关文章:

python - 如何从机器人框架获取测试用例信息

python - MapReduce按Python元组排序

python - 如何将 python 列表的所有子集放入 n 个容器中

javascript - 使用 Prototype 发布复杂的 JSON 对象

python - 更改 Tk 窗口上的标题栏

c# - XAML-Datagrid 跳转到行

python - 列出字典值的理解

c++ - 链表实现链表

python - 在Python中使用元组绘制有向图

python - (Python) 元组/列表赋值