教程地址:零基础入门深度学习(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()
andfilter()
return iterators. If you really need a list and the input sequences are all of equal length, a quick fix is to wrapmap()
inlist()
, 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 ismap()
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 withmap()
from Python 2.x, also wrap the sequences initertools.zip_longest()
.
# python 2.7版本下的写法
map(func, *sequences)
# python 3.7版本下的写法
list(map(func, itertools.zip_longest(*sequences))).
不翻译了,大概的意思就是如果你需要确切的list作为返回值的时候需要使用list()
方法,特别提到了在lambda中的使用。(后面的不会翻译,不理解语境)