Python进阶(四十一)-Python3解决“tuple parameter unpacking is not supported in python3”

Python进阶(四十一)-Python3解决“tuple parameter unpacking is not supported in python3”

  在解决图像配准过程中, 涉及到如下代码,

return reduce(lambda x, (y, z): x | (z << y), enumerate(map(lambda i: 0 if i < avg else 1, im.getdata())), 0)

  在Python3环境下,提示“tuple parameter unpacking is not supported in python3”。翻译成中文就是“拆箱的tuple元组参数在python3中不得到支持”即此种参数形式在python3下废弃了。
  参考PEP 3113 – Removal of Tuple Parameter Unpacking。可发现,在python3中之所以去除tuple元素的参数形式,在PEP 3113中是这样说的“Unfortunately this feature of Python’s rich function signature abilities, while handy in some situations, causes more issues than they are worth. Thus this PEP proposes their removal from the language in Python 3.0.”(Python的这一丰富函数签名属性,虽然在有些使用场景下非常便利–参数的自动拆包,但是其造成的问题多于便利性。)
  上面提到的自动拆箱功能如下所示:

def fxn(a, (b, c), d):
    Pass

  在调用fxn函数时第二个参数就需要保证其长度为2,例如[42, -13],当参数传递时,就会完成参数自动拆箱,即b, c = [42, -13]。
那么,在Python3中,如何取代tuple元素的传参形式呢?PEP 3113中同样给出了答案。
  As tuple parameters are used by lambdas because of the single expression limitation, they must also be supported. This is done by having the expected sequence argument bound to a single parameter and then indexing on that parameter:

lambda (x, y): x + y

will be translated into:

lambda x_y: x_y[0] + x_y[1]

  看到这里,相信大家都明白了,Python3中使用x_y的形式代替(x,y),使其类似于列表的形式,在调用的时候,使用x_y[index]的形式。

《Python进阶(四十一)-Python3解决“tuple parameter unpacking is not supported in python3”》

    原文作者:No Silver Bullet
    原文地址: https://blog.csdn.net/sunhuaqiang1/article/details/70244328
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞