Detailed Explanation of Slicing Iterative List Generation Formula and Generator for Advanced Features of Python

  • 2021-12-11 18:29:11
  • OfStack

Directory Slice Iteration List Generator Iterator

In Python, the less code the better, and the simpler the better. Based on this idea, you need to master the very useful advanced features in Python, the functions that one line of code can achieve, and never write five lines of code. The less code, the more efficient the development.

Slice

tuple, list, string can be sliced


L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']
L[0:3] # ['Michael', 'Sarah', 'Tracy']
L[:3] # ['Michael', 'Sarah', 'Tracy']
L[1:3] # ['Sarah', 'Tracy']
L[-2:] # ['Bob', 'Jack']
L[-2:-1] # ['Bob']

L = list(range(100))
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]
L[:10:2] # [0, 2, 4, 6, 8]
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]

Exercise

Using slicing operation, implement an trim () function, remove the spaces at the beginning and end of the string, and be careful not to call the strip () method of str:


# -*- coding: utf-8 -*-
def trim(s):
    for i in range(0,len(s)):
        if s[0] == ' ':
            s = s[1:]
        elif s[-1] == ' ':
            s = s[:-1]

    return s

Iteration

Any iterable object can act on the for loop, including our custom data type. As long as the iterative conditions are met, the for loop can be used
How to judge that an object is an iterable object? The method is judged by Iterable type of collections. abc module
Python's built-in enumerate function can turn an list into an index-element pair, and can iterate both the index and the element itself in an for loop


for i, value in enumerate(['A', 'B', 'C']):
    print(i, value)

Exercise

Use iteration to find the minimum and maximum values in 1 list and return 1 tuple:


# -*- coding: utf-8 -*-
def findMinAndMax(L):
    max = min = None

    if(len(L)>0):
        L = list(L)
        max = min = L[0]
        for i in L:
            if i>max:
                max = i
            if i<min:
                min = i
    
    return (min,max)

List generation formula

The list generators, known as List Comprehensions, are very simple but powerful generators built into Python that can be used to create 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']

#  List generators can also be generated using two variables list
d = {'x': 'A', 'y': 'B', 'z': 'C' }
[k + '=' + v for k, v in d.items()] # ['y=B', 'x=A', 'z=C']

L = ['Hello', 'World', 'IBM', 'Apple']
[s.lower() for s in L] # ['hello', 'world', 'ibm', 'apple']

In a list generation formula, if … else before for is an expression, while if after for is a filter condition, and else cannot be taken


[x for x in range(1, 11) if x % 2 == 0] # Right
[x for x in range(1, 11) if x % 2 == 0 else 0] # WRONG!

[x if x % 2 == 0 else -x for x in range(1, 11)] # Right
[x if x % 2 == 0 for x in range(1, 11)] # WRONG!

Exercise

If list contains both a string and an integer, the list generator will report an error because there is no lower () method for non-string types. Use the built-in isinstance function to determine whether a variable is a string. Modify the list generator to ensure that it executes correctly by adding an if statement:


# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s,str)]

Generator

If the list elements can be extrapolated according to some algorithm, subsequent elements can be extrapolated through the loop, thus eliminating the need to create a complete list, thus saving a lot of space. In Python, this one-side loop and one-side computation mechanism is called generator: generator.
How to create generator:
1. Change [] of a list generation formula to (), and you will create an generator. After creation, you can get the next element through next, or iterate through for loop (generator is also an iterative object)


#  Generate 1 Iterators 
g = (x * x for x in range(10))
#  Get the following 1 Elements 
next(g) # 0
# for Cyclic traversal 
for n in g:
    print(n)

2. With yield, if a function definition contains the yield keyword, then this function is no longer a normal function, but an generator function. Calling an generator function will return an generator
The generator function is executed every time next () is called, returns when yield statement is encountered, and continues execution from the last returned yield statement when it is executed again
When calling the generator function, we first generate an generator object, and then use the next () function to get the next return value continuously


#  Generation of Fiboracci sequence 
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1
    return 'done'

#  Call 
f = fib(6)
next(f)

# for Loop call 
while True:
    try:
        x = next(g)
        print('g:', x)
    except StopIteration as e:
        print('Generator return value:', e.value)
        break

When you call generator with an for loop, you cannot get the return value of the return statement of generator. If you want to get the return value, you must catch the StopIteration error, and the return value is contained in value of StopIteration

Exercise

Yang Hui's angle is defined as follows:


      1
     / \
    1   1
   / \ / \
  1   2   1
 / \ / \ / \
1   3   3   1

Think of every line as an list, try to write an generator, and continuously output the list of the next line:


# -*- coding: utf-8 -*-
def trim(s):
    for i in range(0,len(s)):
        if s[0] == ' ':
            s = s[1:]
        elif s[-1] == ' ':
            s = s[:-1]

    return s
0

Iterator

An object that can be called by the next () function and continuously return the next value is called an iterator: Iterator.
You can use isinstance () to determine whether an object is an Iterator object:
Generators are all Iterator objects, but list, dict, str are Iterable, but not Iterator. The iter () function can be used to change Iterable such as list, dict, str into Iterator

Why are data types such as list, dict, str not Iterator?
Because the Iterator object of Python represents a data stream, the Iterator object can be called by the next () function and continuously return the next data until an StopIteration error is thrown when there is no data. This data stream can be regarded as an ordered sequence, but we can't know the length of the sequence in advance, and we can only calculate the next data on demand through next () function, so the calculation of Iterator is lazy, and it will only be calculated when the next data needs to be returned.
Iterator can even represent an infinite data stream, such as all natural numbers. It is never possible to store all natural numbers with list.

The for loop of Python is essentially implemented by constantly calling the next () function

The above is the Python Advanced Feature Slicing Iteration List Generation Formula and Generator Details, more information about python Advanced Feature Details please pay attention to other related articles on this site!


Related articles: