Python base (XI)

Today the main content

  • Added: Trinocular operation
  • f-strings
  • Iterator
  • Builder

Added: Trinocular operation

  1. Trinocular operation (ternary operator) Structure:
  • 表达式1 if 条件表达式 else 表达式2
  • c = a if a > b else b
  1. Implementation process:

    • Analyzing conditions, if the conditions are properly assigned to a c
    • If the conditions are not right will be assigned to b c
    a = 10
    b = 20
    c = a if a > b else b  # 三目运算
    print(c)
    
    运行结果:
    20

A, f-strings

  • Before f-strings as we have said, more than python3.6 version can be used for formatting output, very easy today to talk about in detail
  1. f-strings of the form:

    • f"xxxx{传入的变量}xxxx"(Recommended f)
    • F"xxxx{传入的变量}xxxx"(Not recommended F)
    name = "zxd"
    age = 23
    print(f"姓名:{name} 年龄:{age}")
    
    运行结果:
    姓名:zxd 年龄:23
  2. Quotes if you need braces {}, the two {{}}representatives

    print(f"{{'a'}}")  # 用两个大括号表示
    
    运行结果:
    {'a'}
  3. Quotation marks when required, always use two single quotation marks ''represent

    print(f"{{'a'}}")  # 用单引号表示
    
    运行结果:
    {'a'}
  4. Parameters can be passed in three head expression

    a = 10
    b = 10
    print(f"{a if a > b else b}")
    
    运行结果:
    10

Second, the iterator

(A) iterables

  • I say we take a look at iterables before iterator, what is iterables?

    • A value may be a subject that is iterable
    s = "12345"
    lst = [1, 2, 3, 4, 5]
    dic = {1: 1, 2: 2, 3: 3}
    .......
    
    # 这些都是可迭代对象
    • Their common feature is the ability to be a for loop
    s = "12345"
    lst = [1, 2, 3, 4, 5]
    dic = {1: 1, 2: 2, 3: 3}
    
    for el in s:
      print(el)
    for el in lst:
      print(el)
    for el in dic:
      print(el)   
  1. View the official method iterables:

    • Check whether the object has __iter__()a method, as long as there is this method of using objects are all iterables
    • dir()You can view all of the objects function method
    lst = [1, 2, 3, 4, 5]
    print("__iter__" in dir(lst))
    
    运行结果:
    True
  2. Features iteration may object:

    • Space for the concept of time (to save time with plenty of space)
    • advantage:
      • Flexible, each iteration may object has its own method
      • You can directly view the number of elements
      • The value can be repeated
    • Disadvantages:
      • Total memory
  3. Applications: large memory space, when less data than is recommended iterables

(B) iterator

  • Iterator will be understood to be an entity of object iteration, only inherited iteratively (a value of a can), while saving memory (unique advantages)
  • File handle is an iterator
  1. Iterator generating method:

    • The method of generating the same effects of the two
    • iter(可迭代对象)
      • Iterator that generates the iterables
      • Printing is iterator address
    lst = [1, 2, 3, 4, 5]
    l = iter(lst)
    print(l)
    
    运行结果:
    <list_iterator object at 0x0000020BAFCEA940>
    
    • 可迭代对象.__iter__()
      • Iterator that generates the iterables
      • Printing is iterator address
    lst = [1, 2, 3, 4, 5]
    l = lst.__iter__()
    print(l)
    
    运行结果:
    <list_iterator object at 0x000002490EFDA8D0>
    
  2. Iterator value

    • The greatest feature of the iterator is inert mechanism, if not take the initiative to the value of the iterator, iterator will not give you value, but also because of inertia mechanism saves memory
    • next(迭代器)
    lst = [1, 2, 3, 4, 5]
    l = iter(lst)
    print(next(l))
    print(next(l))
    print(next(l))
    print(next(l))
    print(next(l))
    
    运行结果:
    1 2 3 4 5
    
    • 迭代器.__next__()
    lst = [1, 2, 3, 4, 5]
    l = lst.__iter__()
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    
    运行结果:
    1 2 3 4 5
    
    • Each time the function value takes a value only to the iterator sequentially down value, the value can not be repeated, the iterator how many elements can only be next number of times, an error will exceed the maximum number of
    lst = [1, 2, 3, 4, 5]
    l = lst.__iter__()
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    print(l.__next__())
    
    运行结果:
    1 2 3 4 5
    StopIteration
    
  3. Iterator features:

    • Time for space concept (with plenty of time to save space)
    • Save memory
    • Inert mechanism
    • The value can only be down, not back and forth
  4. The nature of the for loop is an iterator

    • Catch exceptions: when the value exceeds the number of elements in the iterator iterator will capture StopIteration exception, thereby terminating the while loop
    lst = [1, 2, 3, 4, 5]
    l = iter(lst)
    while True:
     try:
         print(next(l))
     except StopIteration:  # 捕获异常
         break
    
  5. The value to the same iterator, the iterator will record the value of the internal location, assigned to the variable, the variable will point to the last address value and location

    lst = [1, 2, 3, 4, 5]
    l_iter = iter(lst)
    print(next(l_iter))
    print(next(l_iter))
    print(next(l_iter))
    print(next(l_iter))
    print(next(l_iter))  # l_iter指向取值记录位置
    
    运行结果:
    1 2 3 4 5
    
    • l_iterIterator pointing to the address of every value, l_itera position on the point value
    • It can be understood by an acquaintance to buy something, every time you buy all the previous price
  6. The value to the same iterator, the iterator will record the value of the internal location, if assigned, and each time the value of all the values ​​from the beginning, which is equivalent to start from scratch after each addressing

    lst = [1, 2, 3, 4, 5]
    print(next(iter(lst)))
    print(next(iter(lst)))
    print(next(iter(lst)))
    print(next(iter(lst)))
    print(next(iter(lst)))
    print(next(iter(lst)))  # 每次都从头开始取值
    
    运行结果:
    1 1 1 1 1
    
    • No assignment each time by func()direct addressing, are beginning to value from the head
    • Can not be understood as acquaintances, every time you buy things that are original
  7. Application: The huge memory small amount of data, it is recommended to use an iterator

(C) the relationship between the two

  • Iterator must be iterable, iterables not necessarily iterator
  • Iterators can iter(可迭代对象)and 可迭代对象.__iter__()get

Third, the generator

(A) What is the generator

  • Builder essentially iterators

  • Generator is a iterator to write their own, but only through iterators iter()get function

  • Object generator is not achieved by the data conversion, through code

    • Converted into a list iterator, but the list is still loaded into memory, it did not meet the provincial memory effect
    lst = [1, 2, 3, 4, 5]
    l_iter = iter(lst)
    print(next(l_iter))
    print(next(l_iter))
    print(next(l_iter))
    print(next(l_iter))
    print(next(l_iter))
    
    运行结果:
    1 2 3 4 5
    
    • By Builder truly achieve the province's memory
    def func():
      yield 1
      yield 2
      yield 3
      yield 4
      yield 5
    
    f_gen = func()
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    
    运行结果:
    1 2 3 4 5
    

(B) generator

  1. Implemented via the function generator

    • First look at a function
    def func():
     print(1)
     return 1
    
    print(func())
    
    运行结果:
    1 1
    
    • The function returnreplaced yieldbecomes a generator
    def func():
     print(1)
     yield 1
    
    print(func())
    
    运行结果:
    <generator object func at 0x000001B27042C50>
    
    • If the function is defined, the function name in parentheses is the calling function ; and if the generator is defined, the function name is bracketed was memory address generator
    • yield
      • yield can return multiple values, stored in a tuple
      • various data types can return yield
      • yield can write more and be able to perform
      • performing a location record capable yield
      • Do not write the content behind the yield, default return None
      • yield only downward, not reciprocating, disposable value
  2. Generator of value

    • next(生成器)
    def func():
    yield 1
     yield 2
    yield 3
     yield 4
    yield 5
    
    f_gen = func()
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    
    运行结果:
    1 2 3 4 5
    
    • 生成器.__next__()
    def func():
     yield 1
    yield 2
     yield 3
     yield 4
     yield 5
    
    print(func().__next__())
    print(func().__next__())
    print(func().__next__())
    print(func().__next__())
    print(func().__next__())
    
    运行结果:
    1 2 3 4 5
    
  3. Nature Builder is an iterator, so it has all the characteristics of an iterator

    • Time for space concept (with plenty of time to save space)
    • Save memory
    • Inert mechanism
    • The value can only be down, not back and forth
  4. The value to the same generator, yield will record the value of position, assigned to the variable, the variable will point to the last address value and location

    def func():
     yield 1
     yield 2
     yield 3
     yield 4
     yield 5
    
    f_gen = func()
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))
    print(next(f_gen))  # f_gen指向生成器地址和yiele记录的位置
    
    运行结果:
    1 2 3 4 5
    
  5. A generator to the same value, the yield will record the position values, if assigned, from the beginning of each time values ​​are values, corresponding to the address after each start from scratch

    def func():
     yield 1
     yield 2
     yield 3
     yield 4
     yield 5
    
    print(next(func()))
    print(next(func()))
    print(next(func()))
    print(next(func()))
    print(next(func()))  # 每次都从头开始取值
    
    运行结果:
    1 2 3 4 5
    
  6. If yield value is iterables further objects which can be returned by one

    • yield from
    def func():
     yield from [1, 2, 3]
     yield from [4, 5, 6]
    
    print(next(func()))
    print(next(func()))
    print(next(func()))
    print(next(func()))
    print(next(func()))
    print(next(func()))
    
    运行结果:
    1 2 3 4 5 6
    

Four, three distinguished

(A) iterables

  • It can be used as long as the __iter__()method objects are iterable
  • Iterators and generators are iterables

(B) iterator

  • View an object's memory address, if there iteratoris an iterator
  • It owns __iter__()and __next__()release method is an iterator

(C) generator

  • View an object's memory address, if there generatoris a generator
  • You may be used send()a method that a generator

Guess you like

Origin www.cnblogs.com/tianlangdada/p/11567942.html