我想知道为什么在变量名后添加一个尾随逗号(在本例中是一个字符串)使其成为tuple。即
>>> abc = 'mystring',
>>> print(abc)
('mystring',)
当我打印abc时,它返回tuple ('mystring',)。
另见:stackoverflow.com/questions/7992559/
这是在python中教授基本基本思想的一个很好的问题。
这是重要的逗号,而不是括号。 Python教程说:
A tuple consists of a number of values separated by commas
括号用于在使用逗号的其他地方消除歧义,例如,使您能够嵌套或输入元组作为参数列表的一部分。
请参阅有关元组和序列的Python教程部分
因为这是用一个元素编写元组文字的唯一方法。对于列表文字,必要的括号使语法唯一,但由于parantheses也可以表示分组,将括号中的表达式括起来不会将其转换为元组:您需要一个不同的语法元素,在本例中为逗号。
更新
请参阅上文以获得更好的答案。
原始答案
在python中,元组用括号 strike>表示。
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 pa