多变量声明
Multiple variable declaration
我在Python看到了这个声明,但是不明白是什么意思,也找不到解释:
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
问题是:为什么ret
和thresh
之间有一个逗号?那是什么类型的作业?
这是一个值解包语法。
cv2.threshold(imgray,127,255,0)
returns 一个二元素元组。
使用此语法,您可以将此元组的元素分配给单独的变量 ret
和 thresh
.
这是一个 "tuple" 或 "destructuring" 赋值 - 参见例如Multiple assignment semantics。 cv2.threshold
returns 一个包含两个值的元组,所以它等价于:
temp = cv2.threshold(...)
ret = temp[0]
thresh = temp[1]
参见语言参考中的Assignment Statements:
If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.
您可以使用此语法将元组解包为单个变量,例如。 g.:
a, b = (0, 1)
# a == 0
# b == 1
您的代码与:
result = cv2.threshold(...)
ret = result[0]
thresh = result[1]
我在Python看到了这个声明,但是不明白是什么意思,也找不到解释:
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
问题是:为什么ret
和thresh
之间有一个逗号?那是什么类型的作业?
这是一个值解包语法。
cv2.threshold(imgray,127,255,0)
returns 一个二元素元组。
使用此语法,您可以将此元组的元素分配给单独的变量 ret
和 thresh
.
这是一个 "tuple" 或 "destructuring" 赋值 - 参见例如Multiple assignment semantics。 cv2.threshold
returns 一个包含两个值的元组,所以它等价于:
temp = cv2.threshold(...)
ret = temp[0]
thresh = temp[1]
参见语言参考中的Assignment Statements:
If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.
您可以使用此语法将元组解包为单个变量,例如。 g.:
a, b = (0, 1)
# a == 0
# b == 1
您的代码与:
result = cv2.threshold(...)
ret = result[0]
thresh = result[1]