Slicing iteration generator iterator for summary of advanced features of python

slice:

>>> L = list(range(100))
>>> L
[0, 1, 2, 3, ..., 99]
>>> L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> L[-10:]
[90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
#每隔2个取
>>> L[:10:2]
[0, 2, 4, 6, 8]
#每隔5个取
>>> L[::5]
[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95]
#复制一份
>>> L[:]
[0, 1, 2, 3, ..., 99]

Iteration:

Use for loops to iterate quickly

>>> for x, y in [(1, 1), (2, 4), (3, 9)]:
...     print(x, y)
def findMinAndMax(L):
    if len(L) == 0:
        return (None, None)
    min = L[0]
    max = L[0]
    for x in L:
        if x > max:
            max = x
        if x < min:
            min = x
    return (min, max)

List generator list

>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']
#迭代key value
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> for k, v in d.items():
...     print(k, '=', v)
...
y = B
x = A
z = C

#for 和 if 结合,注意没有else
>>> [x for x in range(1, 11) if x % 2 == 0]
[2, 4, 6, 8, 10]
或者这样 必须有else
>>> [x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = []
for x in L1:
    if isinstance(x, str) and x!= None:
        L2.append(x.lower())

Generator

The generator saves the algorithm. Every time it is called next(g), it calculates the value of gthe next element until the last element is calculated, and there are no more elements, and StopIterationan error is thrown .

forIterate through loops

#list 
>>> L = [x * x for x in range(10)]
#generator
>>> g = (x * x for x in range(10))
>>> for n in g:
...     print(n)
#也可以用函数来生成
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结束 下次调用直接从这里开始执行
>>> g = fib(6)
>>> while True:
...     try:
...         x = next(g)
...         print('g:', x)
...     except StopIteration as e:
...         print('Generator return value:', e.value)
...         break

Generate Yanghui triangle

 def triangles(): 
    n = 1
    L = [1]
    while n < 11:
        yield L
        L2 = L.copy()
        L2.append(1)      
        if len(L2) <= 2:
            pass
        else:
            for x in range(len(L2)):
                if x ==0 or x == len(L2)-1:
                    pass
                else:
                    L2[x]=L[x-1]+L[x]
        L = L2
        n = n + 1 
    return 'done'  

results = []
for t in triangles():
    results.append(t)
    n = n + 1
    if n == 10:
        break

for t in results:
    print(t)

if results == [
    [1],
    [1, 1],
    [1, 2, 1],
    [1, 3, 3, 1],
    [1, 4, 6, 4, 1],
    [1, 5, 10, 10, 5, 1],
    [1, 6, 15, 20, 15, 6, 1],
    [1, 7, 21, 35, 35, 21, 7, 1],
    [1, 8, 28, 56, 70, 56, 28, 8, 1],
    [1, 9, 36, 84, 126, 126, 84, 36, 9, 1]
]:
    print('测试通过!')
else:
    print('测试失败!')

Iterable and Iterator

Iterable objects are not necessarily iterators

>>> from collections.abc 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

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

>>> isinstance(iter([]), Iterator)
True
>>> isinstance(iter('abc'), Iterator)
True

Builder is Iteratoran object, but list, dict, strthough Iterable, is not Iterator.

The list, dict, stretc. Iterablebecome Iteratorpossible to use iter()function

Reference source: https://www.liaoxuefeng.com/wiki/1016959663602400/1017323698112640

Guess you like

Origin blog.csdn.net/li4692625/article/details/109482718