简体   繁体   English

差异访问元组和列表的元素

[英]Difference accessing element(s) of tuple and list

Why is there this difference accessing the element(s) of t when making it a tuple ? 为什么在将它作为tuple时访问t的元素会有这种差异?

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


('ID', 'int')


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


ID
int

I'd expect this to be exactly the same as the first example! 我希望这与第一个例子完全一样! Whereas populating the tuple with more than one element the behavior changes. 尽管使用多个元素填充元组,行为也会发生变化。

>>> 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')

Can somebody give a short explanation? 有人能简单解释一下吗? I'm running python 2.7 我正在运行python 2.7

(('a', 'b')) is the same as ('a', 'b') . (('a', 'b'))('a', 'b')

You actually want (('a', 'b'),) 你真的想要(('a', 'b'),)

This is documented here: 这在此处记录:

5.13. 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 (aka 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: ().) (要创建一个空元组,请使用一对空括号:()。)

Remember, that without this restriction, should the expression (3) * (4) be the multiplication of two numbers, or two tuples? 请记住,没有这个限制,表达式(3) * (4)应该是两个数字或两个元组的乘法吗? Most users would expect that to be the multiplication of numbers. 大多数用户都希望这是数字的乘法。

t = [('ID','int')]

is a tuple in a list. 是一个列表中的元组。

t = (('ID','int'))

is a tuple with brackets around it. 是一个带有括号的元组。

t = ('ID','int'),

is a tuple in a tuple. 是一个元组中的元组。

The , makes the tuple! ,制作元组! The brackets around a tuple are only needed to avoid ambiguity. 只需要一个元组周围的括号来避免歧义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM