zip方法在Python 2 和Python 3中的不同

版权声明:凡由本人原创,如有转载请注明出处https://me.csdn.net/qq_41424519,谢谢合作 https://blog.csdn.net/qq_41424519/article/details/82226715

Python 2 的代码演示:

$ python2
>>> a = zip((1, 2), (3, 4))
>>> a
[(1, 3), (2, 4)]
#  可以看到这里返回的是一个list

Python 3 的代码演示:

$ python3
>>> a = zip((1, 2), (3, 4))
>>> a
<zip object at 0x1007096c8>
# 可以看到这里返回的是一个对象,这里就是2和3的不同点
>>> dir(a)  # 查看a的相关属性

['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__lt__', '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__'] # 这里值得注意的是'__next__'方法,说明a是一个迭代器

# 既然知道了a是一个迭代器,我们也就基本明白了a的用法了 ### 和Python2的区别(一):返回的是一个迭代器,而不是一个list本身

>>> for i in a: print(i) # in 方法 ...

(1, 3) (2, 4)

>>> next(a) # 我们测试__next__方法

Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration # 说明next方法是支持的

>>> a = zip((1, 2), (3, 4)) # 这里需要重新赋值,迭代器只能遍历一次

>>> next(a)

(1, 3) # 运行良好


 

猜你喜欢

转载自blog.csdn.net/qq_41424519/article/details/82226715