为什么在将 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'),)
这在此处记录:
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/