python 3.82 执行语句结果与预测结果不同,是python的错误吗?

在python 3.82 shell下执行语句:

 print([(x,y)for x in [1,y]for y in [3,4]])

执行结果:
[(1, 3), (1, 4), (3.4, 3), (3.4, 4)]
预测结果:
[(1, 3), (1, 4), (2, 3), (2, 4)]
想不出得此执行结果的原因,只能想到是python 3.82版程序的错误,不知哪位仁兄能给解释下原因,谢谢了。

Jason990420
最佳答案
>>> print([(x,y)for x in [1,y]for y in [3,4]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

如果该行没打错字, 那就是语法错误, 正常语法应该是

>>> print([(x,y) for y in [3, 4] for x in [1, y]])
[(1, 3), (3, 3), (1, 4), (4, 4)]

但是

执行结果:
[(1, 3), (1, 4), (3.4, 3), (3.4, 4)]
预测结果:
[(1, 3), (1 , 4), (2, 3), (2, 4)]

所以该代码没出错, 唯一的原因就是

>>> y = 3.4 # 在执行以下代码时, y 为 3.4
>>> print([(x, y) for x in [1, y] for y in [3, 4]])
[(1, 3), (1, 4), (3.4, 3), (3.4, 4)]

按预测结果, 应该是打错一个字, 2打成 y了, 正确的代码应该是

>>> print([(x, y) for x in [1, 2] for y in [3, 4]])
[(1, 3), (1, 4), (2, 3), (2, 4)]
1周前 评论
qlsgqj (楼主) 1周前
讨论数量: 1
Jason990420
>>> print([(x,y)for x in [1,y]for y in [3,4]])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

如果该行没打错字, 那就是语法错误, 正常语法应该是

>>> print([(x,y) for y in [3, 4] for x in [1, y]])
[(1, 3), (3, 3), (1, 4), (4, 4)]

但是

执行结果:
[(1, 3), (1, 4), (3.4, 3), (3.4, 4)]
预测结果:
[(1, 3), (1 , 4), (2, 3), (2, 4)]

所以该代码没出错, 唯一的原因就是

>>> y = 3.4 # 在执行以下代码时, y 为 3.4
>>> print([(x, y) for x in [1, y] for y in [3, 4]])
[(1, 3), (1, 4), (3.4, 3), (3.4, 4)]

按预测结果, 应该是打错一个字, 2打成 y了, 正确的代码应该是

>>> print([(x, y) for x in [1, 2] for y in [3, 4]])
[(1, 3), (1, 4), (2, 3), (2, 4)]
1周前 评论
qlsgqj (楼主) 1周前

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!