JackLovel of Python_ex
6/6/2017 - 10:05 AM

有迭代相关的习题

有迭代相关的习题

#!/usr/bin/env python3
#coding:utf-8

from collections import Iterable, Iterator

# 带yield关键字的生成器函数
def g():
  yield 1
  yield 2
  yield 3

# 使用isinstance函数判断迭达对象和迭达器
print('Iterable? [1, 2, 3]:', isinstance([1, 2, 3], Iterable))
print('Iterable? \'abc\':', isinstance('abc', Iterable))
print('Iterable? 123:', isinstance(123, Iterable))
print('Iterable? g():', isinstance(g(), Iterable))

print('Iterator? [1, 2, 3]:', isinstance([1, 2, 3], Iterator))
print('Iterator? iter([1, 2, 3]):', isinstance(iter([1, 2, 3]), Iterator))
print('Iterator? \'abc\':', isinstance('abc', Iterator))
print('Iterator? 123:', isinstance(123, Iterator))
print('Iterator? g():', isinstance(g(), Iterator))


# 集合数据类型如list、dict、str等是Iterable但不是Iterator,
# 不过可以通过iter()函数获得一个Iterator对象。

''' 使用next()获取Interator类型的对象的值'''

print('next():')
it = iter([1, 2, 3, 4, 5])
print(next(it))
print(next(it))
print(next(it))
print(next(it))
print(next(it))

''' 与上面的等价 '''
print('for x in iter([1, 2, 3, 4, 5]):')
for x in iter([1, 2, 3, 4, 5]):
    print(x)