为什么在python中使用星号扩展元组时使用逗号? [英] Why is comma used while extending tuple by using asterisk in python?

查看:28
本文介绍了为什么在python中使用星号扩展元组时使用逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In the below code if I don't use comma then only one 0 gets printed while if I use comma 0 gets printed five times, why? Is it something to do with the immutable trait of the tuple?

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

输出:0 0 0 0 0

Output: 0 0 0 0 0

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

输出:0

推荐答案

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

It's a syntax thing. What defines the tuple is not the parenthesis, but the presence of the comma:

  • 围绕单个标量表达式的括号用于定义计算顺序:(1 + 2) * 3
  • 由逗号分隔的表达式序列定义了一个元组:1, 2, 3.
    • 如果需要嵌入其他表达式,则可以将这个序列加括号:(1, 2, 3) * 5 是元组 (1,2,3) 重复五次".
    • Parenthesis around a single scalar expression are used to define order of evaluation: (1 + 2) * 3
    • A sequence of expressions separated by commas defines a tuple: 1, 2, 3.
      • This sequence can then be parenthesized if it needs to be embedded in some other expression: (1, 2, 3) * 5 is "the tuple (1,2,3) repeated five times".
      >>> type( (0, ) )
      tuple
      
      >>> type ( (0) )
      int
      
      

      所以 (0) * 5 是整数 0 乘以 5",得到 0.在任何时候都没有涉及元组,因为您使用的语法没有定义元组.

      So (0) * 5 is "the integer 0 multiplied by 5", giving you 0. There's no tuple involved at any point because the syntax you used does not define a tuple.

      这篇关于为什么在python中使用星号扩展元组时使用逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆