Python17_ iterables and iterators

Iterables

def: for loop can act directly on an object referred to as iterables (Iterable). It may be the isinstance () to judge whether an object is iterable object. Iteration: that for the next operation on the basis of a

It may act directly on the data type for generally two types

  1. Set of data types, such as a list, tuple, dic, set, string

  2. A generator, comprising a generator and a generator funcion with yield of

from collections import Iterable
print(isinstance([],Iterable))
print(isinstance(" ",Iterable))
print(isinstance((),Iterable))
print(isinstance({},Iterable))
print(isinstance((x for x in range(10)),Iterable))  #此处isinstance的第一个参数为迭代器
print(isinstance(1, Iterable))  #输出False

Iterator

Not only can act on a for loop, you can be next () function continues to call and returns the next value, until the last throw an error StopIteration, it said it could not continue to return the next value

May be next () call returns the next value and continues referred iterator object (Iterator objects)

Format: next (iterators)

You can use the isinstance () function to determine whether an object is an object Iterator

print(isinstance([],Iterator))
print(isinstance(" ",Iterator))
print(isinstance((),Iterator))
print(isinstance({},Iterator))
print(isinstance((x for x in range(10)),Iterator))  #只有这个是True,因为第一个为迭代器
print(isinstance(1, Iterator))  #输出False

#ps
Itr = x for x in range(5)
#Itr即为一个迭代器
print(next(Itr), next(Itr))

Iterator objects into

Use ITER () method, a list of tuples, the string, the dictionary can be converted iterator

a = iter([1,2,3,4]) #iter()方法如果传两个参数,则第一个必须为函数,会重复调用第一个参数(即函数),直到返回第二个参数为止
print(a.next(1), a.next(1))
#ps:Iterator对象占用的空间一定比原来的列表或元组等可迭代对象占用的空间小

Iterator application

#input方法默认以换行符结束输入

endstr = "end"
str = ""

for line in iter(input,endstr):
    str += (line + "\n")
print(str)

Guess you like

Origin blog.csdn.net/qq_34873298/article/details/89597935