python 3.7中对于tuple

本文介绍了从Python 2.7迁移到Python 3.7时遇到的tuple拆箱处理的不同以及map()方法返回类型的变化。在Python 3.7中,tuple参数拆箱不再支持,map()返回的是迭代器而非列表,需要通过特定方式转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

教程地址:零基础入门深度学习(1) - 感知器

在搭建感知器过程中体会到的python2.7(作者使用的版本)和python 3.7(本宝使用的版本)的区别:
  1. 首先是对于tuple的拆箱处理,如果沿用2.7下的写法会得到提示:

tuple parameter unpacking is not supported in Python 3

# python 2.7版本下的写法
lambda (x, w): x * w, zip(input_vec, self.weights)

# python 3.7版本下的写法
lambda x_w: x_w[1] + rate * delta * x_w[0], zip(input_vec, self.weights)

改动的原因,不知道,也不重要。可以参考PEP 3113 – Removal of Tuple Parameter Unpacking,官方给出的例子是:

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的单行表示限制,tuple参数必须依然能够用在lambda中。可以通过绑定单个参数然后用它们在这个参数中的索引来表示不同的变量。

# python 2.7版本下的写法
lambda (x, y): x + y

# python 3.7版本下的写法
lambda x_y: x_y[0] + x_y[1]

  2. map()方法返回的结果类型的改变
  参考 What’s New In Python 3.0,其中仅次于print()由语句输出改变为方法的,就是map()返回类型的改变。

map() and filter() return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrap map() in list(), e.g. list(map(...)), but a better fix is often to use a list comprehension (especially when the original code uses lambda), or rewriting the code so it doesn’t need a list at all. Particularly tricky is map() invoked for the side effects of the function; the correct transformation is to use a regular for loop (since creating a list would just be wasteful).

If the input sequences are not of equal length, map()will stop at the termination of the shortest of the sequences. For full compatibility with map() from Python 2.x, also wrap the sequences in itertools.zip_longest().

# python 2.7版本下的写法
map(func, *sequences)
# python 3.7版本下的写法
list(map(func, itertools.zip_longest(*sequences))).

不翻译了,大概的意思就是如果你需要确切的list作为返回值的时候需要使用list()方法,特别提到了在lambda中的使用。(后面的不会翻译,不理解语境)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值