有人可以解释这种行为:
a = b = c = 1, 2, 3
a # => [1, 2, 3]
b # => 1
c # => 1
在作业a = b = c = 1, 2, 3
中,变量a
,b
和c
应分配[1, 2, 3]
。有什么想法吗?
答案 0 :(得分:5)
有人可以解释为什么会发生这种情况
@shivam already answered这个问题,但添加一些括号可能会更清楚地澄清事情。
a = b = c = 1, 2, 3
被解释为:
a = [(b = (c = 1)), 2, 3]
表达式按以下顺序计算:
c = 1
b = ( )
a = [( ), 2, 3]
应为变量
a
,b
和c
分配[1, 2, 3]
要获得预期结果,您可以写:
a = b = c = [1, 2, 3]
被解释为:
a = (b = (c = [1, 2, 3]))
并按此顺序进行评估:
c = [1, 2, 3]
b = ( )
a = ( )
答案 1 :(得分:4)
你感到困惑
a=b=c=1,2,3
实际上是:
a = (b = c = 1), 2, 3
离开
c = 1 # => 1
b = c # => 1
a = 1,2,3 # => [1, 2, 3]
答案 2 :(得分:-2)
要做你正在谈论的事情你应该做如下:
a,b,c = 1,2,3
p a #=> 1
p b #=> 2
p c #=> 3