我没发现问题,这与文档相符:class tuple(object)
| tuple() -> empty tuple
| tuple(iterable) -> tuple initialized from iterable's items
|
| If the argument is a tuple, the return value is the same object.
所以,list('abc')的计算结果总是['a', 'b', 'c'],这是一个iterable。在
所以在第一个示例(tuple(['a', 'b', 'c']))中,结果是从iterable的项初始化的元组。一、 e.(“a”、“b”、“c”)。在
第二个示例获取第一个示例(元组)的结果,并再次将其传递给tuple()函数。如文档所述(最后一行),传递元组时的返回值是与我们的结果匹配的同一个对象。在
第三个,再一次,the docs告诉我们我们需要知道的:A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses).
最后,最后两个示例(tuple([1])和tuple([1],))都生成一个单元素元组,因为您传递的是长度为1的iterable。docs再次声明(在顶部):元组是从iterable的项初始化的。在
因此,总结一下,需要逗号的情况是当您想要创建一个包含一个元素的元组时。但是,如果传递一个长度为1的iterable,这是不必要的,因为Python知道您没有对表达式求值。在
为了完整起见,这种笨拙的语法是不可避免的,因为像:(1 + 2) * 3这样的语句的计算结果是(3, 3, 3),而不是预期的{}。因此,您必须特意添加一个逗号:(1 + 2,) * 3以得到(3, 3, 3)的结果,这非常有意义。在
|