为什么在python中使用星号扩展元组时使用逗号?

2024-04-25 00:29:31 发布

您现在位置:Python中文网/ 问答频道 /正文

在下面的代码中,如果我不使用逗号,那么只打印一个0,而如果我使用逗号0,则打印五次,为什么?这与元组的不变特性有关吗?你知道吗

 food = (0,) * 5  # comma used
 print (*food)

输出:0 0 0 0

 food = (0) * 5  # comma not used
 print (*food)

你知道吗输出:0你知道吗


Tags: 代码foodnot特性used元组print逗号
3条回答

因为:

>>> (0)
0
>>>

所以0 * 50,而:

>>> (0,)
(0,)
>>> 

保持元组的类型。你知道吗

Tuples and Sequences在文档中,一个带有一个项的元组是通过在值后面加逗号来构造的

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). Ugly, but effective. For Example

>>> t=('hello')
>>> t
'hello'
>>> type(t)
<class 'str'>
>>> t1=('hello',)
>>> t1
('hello',)
>>> type(t1)
<class 'tuple'>
>>>

这是个语法问题。定义元组的不是括号,而是逗号的存在:

  • 单个标量表达式周围的括号用于定义求值顺序:(1 + 2) * 3
  • 由逗号分隔的表达式序列定义了一个元组:1, 2, 3
    • 如果这个序列需要嵌入到其他表达式中,则可以将其括起来:(1, 2, 3) * 5是“元组(1,2,3)重复五次”。你知道吗
  • 特别是对于单个项元组,语法需要一个尾随逗号来区分它与带括号的表达式:0,是一个只包含元素0的元组;通常,如果要将此表达式嵌入一个更大的表达式中,您会立即希望将其插入括号,例如(0,) * 5(“由零组成的元组,乘以5倍”)。而0(0)都表示“整数零”(后一种形式的括号)。你知道吗
>>> type( (0, ) )
tuple

>>> type ( (0) )
int

所以(0) * 5是“整数0乘以5”,等于0。任何时候都不涉及元组,因为您使用的语法没有定义元组。你知道吗

相关问题 更多 >