问题
I saw this declaration in Python, but I don't understand what it means and can't find an explanation:
ret, thresh = cv2.threshold(imgray, 127, 255, 0)
The question is: why is there there a comma between ret
and thresh
? What type of assignment is that?
回答1:
That's a "tuple" or "destructuring" assignment - see e.g. Multiple assignment semantics. cv2.threshold
returns a tuple containing two values, so it's equivalent to:
temp = cv2.threshold(...)
ret = temp[0]
thresh = temp[1]
See Assignment Statements in the language reference:
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.
回答2:
This is a value unpacking syntax.cv2.threshold(imgray,127,255,0)
returns a two element tuple.
With this syntax you assign elements of this tuple to separate variables ret
and thresh
.
回答3:
You can use this syntax to unpack tuples to single variables, e. g.:
a, b = (0, 1)
# a == 0
# b == 1
Your code is the same as:
result = cv2.threshold(...)
ret = result[0]
thresh = result[1]
来源:https://stackoverflow.com/questions/29676708/multiple-variable-declaration