Million annual salary python road - day11 - iterator

3.1 iterables

  3.1.1 iterables defined

        **在python中,但凡内部含有 _ _ iter_ _方法的对象,都是可迭代对象**。

  3.1.2 view an object internal methods

The internal object contains the source code to see what methods in addition to what other way to solve it? With, of course, by dir () to judge what object has a method

s1 = 'alex'
print(dir(s1))

dir () returns a list, which contains all the object as a string method name. In this way we can determine an object in python is not the iterable:

s1 = 'alex'
i = 100
print('__iter__' in dir(i))  # False
print('__iter__' in dir(s1))  # True

  3.1.3 Summary :

From a professional standpoint: _ _ Whenever objects containing internal iter__ methods are iterable.

Iterables _ _iter__ if there can be judged by the judging method of the object.

Iterables of advantages :

You can visually see the data inside.

Iterables of disadvantages :

1. take up memory.

2. iterables not iterative values (other than the index, key removed).

In fact, for the iterables loop through a series of operations into a iterator

3.2 iterator

  3.2.1 the definition of an iterator

From a professional standpoint: iterator is an object: to achieve a free parameter _ Next _ method returns the next element in the sequence, if no element, then the iterator StopIteration exception thrown is also achieved .python __ __ ITER method may be iterative so iterators. From "smooth python"

** in python, contained inside _ _ _ Iter method and containing _ _ _ Next iterator is an object method. **

  3.2.2 How to determine whether the object is an iterator

ok, so we have this definition, we can determine the number of objects is not an iterator or a iterables, please judge these objects: str list tuple dict set range of file handles which is an iterator, which is iterables:

o1 = 'alex'
o2 = [1, 2, 3]
o3 = (1, 2, 3)
o4 = {'name': '太白','age': 18}
o5 = {1, 2, 3}
f = open('file',encoding='utf-8', mode='w')
print('__iter__' in dir(o1))  # True
print('__iter__' in dir(o2))  # True
print('__iter__' in dir(o3))  # True
print('__iter__' in dir(o4))  # True
print('__iter__' in dir(o5))  # True
print('__iter__' in dir(f))  # True

print('__next__' in dir(o1))  # False
print('__next__' in dir(o2))  # False
print('__next__' in dir(o3))  # False
print('__next__' in dir(o4))  # False
print('__next__' in dir(o5))  # False
print('__next__' in dir(f))  # True
f.close()

Can verify the code above, these objects before we learned, only the file handle is an iterator, the rest of those data types are iterable.

  3.2.3 How iterables iterator converted to:

l1 = [1, 2, 3, 4, 5, 6]
obj = l1.__iter__()
# <list_iterator object at 0x000002057FE1A3C8>
# 或
obj = iter(l1)
print(obj)
# <list_iterator object at 0x102cc67f0>

 3.2.4 iterator values:

Iterables been iterative value is not (removal index, slicing and Key), but can be converted to the iterator, using the value of the iterator is __next __ ():

l1 = [1, 2, 3,]
obj = l1.__iter__()  # 或者 iter(l1)
# print(obj)  # <list_iterator object at 0x000002057FE1A3C8>
ret = obj.__next__()
print(ret)
ret = obj.__next__()
print(ret)
ret = obj.__next__()
print(ret)
ret = obj.__next__()  # StopIteration
print(ret)
# 迭代器利用next取值:一个next取对应的一个值,如果迭代器里面的值取完了,还要next,
# 那么就报StopIteration的错误。

  3.2.5 while simulation for internal circulation mechanism:

We have just mentioned, the circulation loop must be a target for iterable, but that does not mean you can iterables value, because the internal mechanism for loop is: convert iterables into an iterator, then use the next be value. Finally, exception handling process StopIteration thrown.

l1 = [1, 2, 3, 4, 5, 6]
# 1 将可迭代对象转化成迭代器
obj = iter(l1)
# 2,利用while循环,next进行取值
while 1:
    # 3,利用异常处理终止循环
    try:
        print(next(obj))
    except StopIteration:
        break

  3.2.6 Summary:

From a professional standpoint: in python, comprising _ internal ITER _ is to iterables
From a professional standpoint: in python, contained inside _ ITER _ _ _ methods and containing Next objects _ method iterators.

Iterator advantages:

Save memory. Iterator equivalent to only one data space in memory: because each piece of data will be released on values ​​in memory, load current of the record.

Inert mechanism. next time, take a value will not be more than the value.

Iterator has a good pattern can explain the two above: iteration is the cornerstone of data processing. When the memory does not fit too many data sets, we need to find a way to get the data item inert, that demand fetch one data item. This is an iterative mode.

Iterator disadvantages:

Not intuitive view of data inside.

When the value is not turning back, only has value down.

l1 = [1, 2, 3, 4, 5, 6]
obj = iter(l1)      # 等于 obj = l1.__iter__()

for i in range(2):
    print(next(obj))

for i in range(2):
    print(next(obj))

3.3 iteration comparable iterator object

Iterables:

Is a proprietary method more flexible operation (such as a list, CRUD dictionaries, and the like commonly used method of operation of the string), more intuitive, but take up memory, and such loop iterations can not be a value directly dataset.

Application : When you focus on flexibility for data processing, and sufficient memory space, the data set is set to iterables is the clear choice.

Iterator:

It is a very save memory, can record the position values, the values ​​may cycle through + _ _ next _ _ direct method, but not intuitive method of operating a single set of data comparison.

Application : When your data is too large, large enough to explode your memory or you to save memory to the first factor , the data set is set iterator is a good choice. (Refer to why the python file handle is set to the iterator).

Guess you like

Origin www.cnblogs.com/zhangchaoyin/p/11221143.html