Sta*_*tan 105 python syntax tuples
在单个元素元组的情况下,需要尾随逗号.
a = ('foo',)
Run Code Online (Sandbox Code Playgroud)
那个有多个元素的元组怎么样?似乎尾随逗号是否存在,它们都是有效的.它是否正确?在我看来,使用尾随逗号更容易编辑.这是一种糟糕的编码风格吗?
a = ('foo1', 'foo2')
b = ('foo1', 'foo2',)
Run Code Online (Sandbox Code Playgroud)
Jef*_*ado 85
单项元组仅需要消除定义元组或括号括起的表达式的歧义.
(1) # the number 1 (the parentheses are wrapping the expression `1`)
(1,) # a 1-tuple holding a number 1
Run Code Online (Sandbox Code Playgroud)
对于多个项目,不再需要它,因为它非常清楚它是一个元组.但是,允许尾随逗号使用多行更容易定义它们.您可以添加到结尾或重新排列项目而不会破坏语法,因为您在事故中遗漏了逗号.
例如,
someBigTuple = (
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
#...
10000000000,
)
Run Code Online (Sandbox Code Playgroud)
请注意,这也适用于其他集合(例如,列表和词典),而不仅仅是元组.
Dun*_*can 67
在除了空元组之外的所有情况下,逗号都是重要的.只有在出于其他语法原因需要时才需要括号:区分元组与一组函数参数,运算符优先级或允许换行符.
元组,列表或函数参数的尾随逗号是很好的样式,特别是当你有一个很长的初始化分割成多行时.如果你总是包含一个尾随逗号,那么你不会在末尾添加另一行,期望添加另一个元素,而只是创建一个有效的表达式:
a = [
"a",
"b"
"c"
]
Run Code Online (Sandbox Code Playgroud)
假设它是作为一个后来扩展的2元素列表开始的,它可能不是很明显的方式出错了.始终包括尾随逗号并避免该陷阱.
asm*_*rer 46
尾随逗号的另一个优点是它使差异看起来更好.如果你开始
a = [
1,
2,
3
]
Run Code Online (Sandbox Code Playgroud)
并改为
a = [
1,
2,
3,
4
]
Run Code Online (Sandbox Code Playgroud)
差异看起来像
a = [
1,
2,
- 3
+ 3,
+ 4
]
Run Code Online (Sandbox Code Playgroud)
如果你开始使用尾随逗号,比如
a = [
1,
2,
3,
]
Run Code Online (Sandbox Code Playgroud)
然后差异就是
a = [
1,
2,
3,
+ 4,
]
Run Code Online (Sandbox Code Playgroud)
另外,请考虑您想要的情况:
>>> (('x','y'))*4 # same as ('x','y')*4
('x', 'y', 'x', 'y', 'x', 'y', 'x', 'y')
#Expected = (('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y'))
Run Code Online (Sandbox Code Playgroud)
所以在这种情况下,外括号只不过是对括号进行分组.要使它们成为元组,您需要添加一个尾随逗号.即
>>> (('x','y'),)*4
(('x', 'y'), ('x', 'y'), ('x', 'y'), ('x', 'y'))
Run Code Online (Sandbox Code Playgroud)
小智 6
这是一个简单的答案。
a =(“ s”)是一个字符串
和
a =(“ s”,)是具有一个元素的元组。
对于一个元素元组,Python需要附加逗号,以区分字符串和元组。
例如,在python控制台上尝试:
a =(“ s”)
a = a +(1,2,3)
追溯(最近一次通话):
文件stdin,第1行,在模块中
TypeError:无法连接“ str”和“ tuple”对象