Multiple variable declaration

自作多情 提交于 2019-12-29 10:03:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!