python2 与 python3的区别 (3)

python2里,迭代器有一个next()方法,用来返回序列的下一项。在python3里同样成立。但是有一个新的全局的函数next(),它使用一个迭代器作为参数。

python2 python3 备注
anIterator.next()   next(anIterator)      
a_function_that_returns_an_iterator().next()   next(a_function_that_returns_an_iterator())      
class A: def next(self): pass   class A : def next(self): pass      
class A: def next(self, x, y): pass   no change      
next = 42 for an_iterator in a_sequence_of_iterators: an_iterator.next()   next =42 for an interator in a_sequence_of_iterators: an_iterator.next()      

全局函数FILTER()

在python2里,filter()方法返回一个列表,这个列表是通过一个返回值为True或False的函数来检测序列里的每一项的道德。在python3中,filter()函数返回一个迭代器,不再是列表。

python2 python3 备注
filter(a_function, a_sequence)   list(filter(a_function, a_sequence))      
list(filter(a_function, a_sequence))   no change      
filter(None, a_sequence)   [i for i in a_sequence if i ]      
for i in filter(None, a_sequence):   no change      
[i for i in filter(a_function, a_sequence)]   no change      

MAP()

跟filter()的改变一样,map()函数现在返回一个迭代器,python2中返回一个列表。

python2 python3 备注
map(a_function,\'PapayaWhip\'   list(map(a_function, \'PapayaWhip\'))      
map(None, \'PapayaWhip\'   list(\'PapayWhip\')      
map(lambda x: x+1, range(42))   [x+1 for x in range(42)]      
for i in map(a_function, a_sequence):   no change      
[i for i in map(a_function, a_sequence)]   no change      

REDUCE()

在python3里,reduce()函数已经从全局名字空间移除,现在被放置在fucntools模块里。

python2 python3 备注
reduce(a,b,c)   from functools import reduce reduce(a, b, c)      

APPLY()

python2有一个叫做apply()的全局函数,它使用一个函数f和一个列表[a,b,c]作为参数,返回值是f(a,b,c).可以直接调用这个函数,在列表前添加一个星号作为参数传递给它来完成同样的事情。在python3里,apply()函数不再存在;必须使用星号标记。

python2 python3 备注
apply(a_function, a_list_of_args   a_function(*a_list_of_args)      
apply(a_function, a_list_of_args, a_dictionary_of_named_args)   a_function(*a_list_of_args, **a_dictionary_of_named_args)      
apply(a_function, a_list_of_args + z)   a_function(*a_list_of_args + z)      
apply(aModule.a_function, a_list_of_args)   aModule.a_function(*a_list_of_args)      

INTERN()   python2里,你可以用intern()函数作用在一个字符串上来限定intern以达到性能优化,python3里,intern()函数转移到sys模块里。

python2 python3 备注
intern(aString)   sys.intern(aString)   --------  

EXEC

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgzxwf.html