Python 后跟逗号和换行符的变量含义
Python meaning of variables followed by comma and newline
当我有一个变量后跟一个逗号时,我看到了一些奇怪的打印输出,我想知道 Python 解释器在遇到它时到底做了什么。
def new_func():
x = 1
y = 2
return x,y
x = 0
x,
y = new_func()
print(x,y)
输出:0 (1,2)
那么到底打印了什么? Python 是如何处理 x,↵
的?我可以用它做什么?
一般来说,在 Python 中,逗号构成一个元组。
换行符没有任何作用。
例如i = 1
,相当于i = (1,)
一般示例:
>>> 1
1
>>> 1,
(1,)
您的情况:
>>> x = 0
>>> type(x)
int
>>> x,
(0,) # this is just the printed version of x as tuple
>>> x = x, # actual assignment to tuple
>>> type(x)
tuple
当我有一个变量后跟一个逗号时,我看到了一些奇怪的打印输出,我想知道 Python 解释器在遇到它时到底做了什么。
def new_func():
x = 1
y = 2
return x,y
x = 0
x,
y = new_func()
print(x,y)
输出:0 (1,2)
那么到底打印了什么? Python 是如何处理 x,↵
的?我可以用它做什么?
一般来说,在 Python 中,逗号构成一个元组。 换行符没有任何作用。
例如i = 1
,相当于i = (1,)
一般示例:
>>> 1
1
>>> 1,
(1,)
您的情况:
>>> x = 0
>>> type(x)
int
>>> x,
(0,) # this is just the printed version of x as tuple
>>> x = x, # actual assignment to tuple
>>> type(x)
tuple