Python 为什么在变量名后添加尾随逗号使其成为元组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3750632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why does adding a trailing comma after a variable name make it a tuple?
提问by Avadhesh
I want to know that why adding a trailing comma after a variable name (in this case a string) makes it a tuple. i.e.
我想知道为什么在变量名(在本例中为字符串)后添加尾随逗号使其成为tuple. IE
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
When I print abcit returns the tuple('mystring',).
当我打印abc它时返回tuple('mystring',).
采纳答案by Ben James
It is the commas, not the parentheses, which are significant. The Python tutorial says:
重要的是逗号,而不是括号。Python教程说:
A tuple consists of a number of values separated by commas
元组由多个以逗号分隔的值组成
Parentheses are used for disambiguation in other places where commas are used, for example, enabling you to nest or enter a tuple as part of an argument list.
括号用于在其他使用逗号的地方消除歧义,例如,使您能够嵌套或输入元组作为参数列表的一部分。
回答by Manoj Govindan
Update
更新
See above for a much better answer.
请参阅上文以获得更好的答案。
Original Answer
原答案
In python a tuple is indicated by parenthesis.
在 python 中,元组用括号表示。
Tuples are not indicated by the parentheses. Any expression can be enclosed in parentheses, this is nothing special to tuples. It just happens that it is almost always necessary to use parentheses because it would otherwise be ambiguous, which is why the
__str__and__repr__methods on a tuple will show them.
元组没有用括号表示。任何表达式都可以用括号括起来,这对元组来说没什么特别的。碰巧几乎总是需要使用括号,因为否则它会产生歧义,这就是为什么元组上的
__str__和__repr__方法会显示它们。
I stand corrected (all I've been doing today. Sigh).
我站得更正了(我今天所做的一切。叹气)。
For instance:
例如:
abc = ('my', 'string')
What about single element tuples? The parenthesis notation still holds.
单元素元组呢?括号表示法仍然成立。
abc = ('mystring',)
For all tuples, the parenthesis can be left out but the comma needs to be left in.
对于所有元组,括号可以省略,但逗号需要留在里面。
abc = 'mystring', # ('mystring',)
Or
或者
abc = 'my', 'string', # ('my', 'string',)
So in effect what youwere doing was to create a single element tupleas opposed to a string.
所以实际上你所做的是创建一个单元素元组而不是一个字符串。
The documentationclearly says:
该文件明确表示:
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.
包含至少一个逗号的表达式列表产生一个元组。元组的长度是列表中表达式的数量。表达式从左到右计算。
回答by Philipp
Because this is the only way to write a tuple literal with one element. For list literals, the necessary brackets make the syntax unique, but because parantheses can also denote grouping, enclosing an expression in parentheses doesn't turn it into a tuple: you need a different syntactic element, in this case the comma.
因为这是用一个元素编写元组文字的唯一方法。对于列表文字,必要的括号使语法唯一,但由于括号也可以表示分组,将表达式括在括号中不会将其转换为元组:您需要一个不同的语法元素,在这种情况下是逗号。
回答by Zv_oDD
In the question's example, you assigned the variable 'abc' to a Tuple with a length of 1.
在问题的示例中,您将变量 'abc' 分配给一个长度为 1 的元组。
You can do multiple assignments with this similar syntax:
您可以使用以下类似的语法进行多项分配:
x,y = 20,50
Also note that the print statement has a special understanding for ending a print statement with a comma; This tells print to omit the trailing newline.
还要注意print语句对以逗号结束print语句有特殊的理解;这告诉 print 省略尾随的换行符。
print 'hello',
print 'world'
result:
结果:
hello world
回答by Mukti
Unpacking multi-element tuple:
解包多元素元组:
a, b = (12, 14)
print type(a)
Output:
输出:
int
整数
Unpacking single-element tuple:
解包单元素元组:
a, = (12, )
print type(a)
Output:
输出:
int
整数
Otherwise:
除此以外:
a = (12,)
print type(a)
Output:
输出:
tuple
元组
回答by PaulG
When you see a comma after a single value, that value is interpreted as the datatype 'tuple'.
当您在单个值后看到逗号时,该值被解释为数据类型“元组”。
Here is a little something I've learned through experience that may apply to some of you:
以下是我通过经验学到的一些东西,可能适用于你们中的一些人:
If you're a musician, the word tuple may be confusing, since the words tuple and triple are used to describe groupings of notes that are used within a certain type of time signature that they are not strictly compatible with. For example a grouping of two eighth notes played as if the time signature were 4/4 (straight feel) when the time signature is 6/8 (triplet feel). Or vice versa a triplet played in 4/4 time. This leads the novice programmer to perhaps interpret a tuple as a pair of values.
如果您是音乐家,那么元组这个词可能会令人困惑,因为元组和三元组这两个词用于描述在某种类型的拍号中使用的音符分组,但它们并不严格兼容。例如,当拍号为 6/8(三连音感觉)时,两个八分音符的组合就好像拍号为 4/4(直感)一样演奏。反之亦然,以 4/4 时间播放三连音。这导致新手程序员可能将元组解释为一对值。
This isn't the same kind of tuple as you see in programming. These tuples are an immutable (un-alterable once assigned) sequence data type that can hold any number of values but can be considered to be transferred together as if they were all enclosed between to parentheses, or in other words, a tuple of parentheses.
这与您在编程中看到的元组类型不同。这些元组是不可变的(一旦分配就不可更改)序列数据类型,它可以保存任意数量的值,但可以被视为一起传输,就好像它们都包含在括号之间,或者换句话说,是一个括号元组。
You can't add or delete stuff from a tuple once it is assigned, so it is usually used to pack and unpack variables. I use it frequently to return multiple values from a function:
一旦分配了元组,您就无法从元组中添加或删除内容,因此它通常用于打包和解包变量。我经常使用它从函数返回多个值:
def somefunction_foo(some_data_file):
map1 = dict()
map2 = dict()
map3 = dict()
with open(datafile, 'r') as file: # auto-close the file after this block
for row in file:
pass
# don't actually pass, but
# fill each map with specific data from the same file
return map1, map2, map3 # I'm returning a tuple, but without parenthesis

