Advanced Features: Slice iteration list generator, the generator iterator

slice

Get a list or some elements of the tuple
L = [ 'Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L [0: 3] represents fetch begins at index 0, until the index 3, but not including the index 3. That index 0,1,2, just three elements
just write [:] can be copied as a list

String 'xxx' may be regarded as a list, each element is a character
'xxx' [: 3]

Iteration is the cycle

Given a list or tuple, we can traverse the list or tuple through the for loop, we call this traversal iteration (Iteration)
iteration dict

>>> d = {'a': 1, 'b': 2, 'c': 3}
>>> for key in d:
...     print(key)
...
a
c
b

By default, dict iteration is key. If you want iteration value, can be used for value in d.values ​​(), If you want iteration key and value, can be used for k, v in d.items ()

String iteration

>>> for ch in 'ABC':
...     print(ch)
...
A
B
C

How to determine an object is iterable

>>> from collections import Iterable
>>> isinstance('abc', Iterable) # str是否可迭代
True
>>> isinstance([1,2,3], Iterable) # list是否可迭代
True
>>> isinstance(123, Iterable) # 整数是否可迭代
False

List of Formula

That list of Formula List Comprehensions, Python is a very simple but powerful built-in can be used to create a list of the formula

ll=list(range(1,10))
print(ll)


生成[1x1, 2x2, 3x3, ..., 10x10]
[x * x for x in range(1, 13)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144]


[x * x for x in range(1, 11) if x % 2 == 0]

两层循环:
[m + n for m in 'ABC' for n in 'XYZ']

列出目录
import os
[d for d in os.listdir('/')]

字典
d = {'x': 'A', 'y': 'B', 'z': 'C' }
for k, v in d.items():
     print(k, '=', v)
[k + '=' + v for k, v in d.items()]

变小写
L = ['Hello', 'World', 'IBM', 'Apple']
[i.lower()  for i in L ]

Builder

If the list element can be calculated out in accordance with an algorithm
in Python, while circulating mechanism for this calculation is known as a generator: generator

To create a generator, there are many ways. The first method is very simple, as long as a list of the formula [] into (), creates a generator

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>

创建L和g的区别仅在于最外层的[]和(),L是一个list,而g是一个generator。
generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素

>>> g = (x * x for x in range(10))
>>> for n in g:
...     print(n)

Feibolaqi number of columns

def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        print(b)
        a, b = b, a + b
        n = n + 1
    return 'done'
a, b = b, a + b

相当于:
t = (b, a + b) # t是一个tuple
a = t[0]
b = t[1]

上面的函数和generator仅一步之遥。要把fib函数变成generator,只需要把print(b)改为yield b:
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通函数,而是一个generator: 

Pascal's Triangle

# -*- coding: utf-8 -*-

def triangles():
    L = [1]
    while 1:
        yield L
        L = [0] + L + [0]
        L = [L[i] + L[i + 1] for i in range(len(L) - 1)]
        
g = triangles()

for i in range(1,10):
    print(next(g))

Iterator

A class is a collection of data types, such as a list, tuple, dict, set, str like;

One is the generator, comprising a generator and a band of yield generator function.

These can act directly on an object referred to as a for loop iterables: Iterable.

Can use the isinstance () determines whether an object is an object Iterable

>>> from collections import Iterable
>>> isinstance([], Iterable)
True
>>> isinstance({}, Iterable)
True
>>> isinstance('abc', Iterable)
True
>>> isinstance((x for x in range(10)), Iterable)
True
>>> isinstance(100, Iterable)
False

Not only can act on the generator for circulation, can also be next () function continues to call and returns the next value, until the last error thrown StopIteration said it could not continue to return the next value.

May be next () function returns the call and continue to the next value of an object called an iterator: Iterator
generators are Iterator objects, but list, dict, str though Iterable, not the Iterator.

The list, dict, str becomes like Iterable Iterator may be used ITER () function:
https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640

Guess you like

Origin www.cnblogs.com/g2thend/p/11798954.html