Function generator, built-in functions derivation and python

Function generator, built-in functions derivation and python

Function generator

Defined generator

In Python, using a function generator is referred to as yield (generator).

The difference is that with an ordinary function, the generator is a return iterator function can only be used to iterate operation, more simply understood generator is a iterator.

During the call generator is running, each encounter yield function pauses and save all of the current operating information, the return value of yield, and the next execution of the next () continue to operate from its current position method.

Calling a generator function, it returns an iterator object.

The difference between the generator and the iterator

Builder is the program developers have written a special iterator

Iterator for the python built-in objects

Iterables, iterators and generators relationship between the three:

Generators are built

  • Construction generator function
  • Construction generator derivations
  • and a module for built-in functions python

Generator function

def func():
    print(111)
    yield 222   #关键字,当函数中出现yield关键字时候,说明我们想要声明一个生成器
g = func()   #生成器
print(next(g))   #与__next__()方法一样
# 结果:
<generator object func at 0x0000028A1D5BFF10>   #生成器对象内存地址
111
222

A generator function and next is one to yield, when the number exceeds the yield next, the program being given Stopiteration

yield and return the difference:

In general the return function is provided only one, his role is to terminate the function, and to the return value of the function's execution.

yield the generator function may be provided in a plurality, and that he does not terminate function, next will yield the corresponding acquisition element generates.

lst = []
def func():
    for i in range(10000):   #列表方式存储,非常占用内存
        lst.append(i)
print(i)        

def func():
    for i in range(10000):
        yield i     # yield起阻塞作用,用1取1
g = func()
for j in range(50):
    print(next(g))
# 结果为0-49
def func():
    lst1 = ["牛羊配","老奶奶花生米","卫龙","虾扯蛋","米老头","老干妈"]
    lst2 = ["小浣熊","老干爹","亲嘴烧","麻辣烫","黄焖鸡","井盖"]
    yield from lst1
    yield from lst2   # yield from -- 将可迭代对象元素逐个返回

g = func()
print(next(g))
print(next(g))
print(next(g))
# 结果:
牛羊配
老奶奶花生米
卫龙

trap:

def func():
    yield 1
    for i in range(10):
        yield i
print(func().__next__())
print(func().__next__())  #重复制造杯子(生成器)
# 结果:
1
1

summary:

In the function return is rewritten to yield a generator

yield will record the execution position

return and yield are returned, return could write more, but performed only once, yield can write more, you can also return many times

The __next a __ () corresponding to a yield

Generator may be used for loop to obtain the value

yield from - will return iterable elements one by one

Temporary pause in yield can function inside a for loop and while loops

Derivations

List comprehensions

lst = []
for i in range(10):
    lst.append(i)
print(lst)
# 结果:
[0,1,2,3,4,5,6,7,8,9]

print([i for i in range(10)])
# 结果:
[0,1,2,3,4,5,6,7,8,9]

Cycle mode

[变量(加工后的变量)for 循环]
print([i for i in range(0,10,2)]) #10以内所有偶数

Screening mode

[变量(加工后的变量)for 循环 if 条件]
print([i for i in range(10) if i%2==1]) #10以内所有奇数
print([f"python{i}期" for i in range(1,25) if i%2==0]) #python24期内所有偶数期

Generator expressions

Cycle mode

(变量(加工后的变量)for 循环)
g = (i for i in range(10))
print(next(g))
print(next(g))
# 结果:
0
1

Screening mode

(变量(加工后的变量)for 循环 if 条件)
g = (i for i in range(50) if i%5 == 0)
print(next(g))
print(next(g))
# 结果
0
5

Other derivations

# 字典推导式:
print({i:i+1 for i in range(10)})
print({i:i+1 for i in range(10) if i % 2 == 0})
# {键:值 for循环 加工条件}
# 集合推导式:
print({i for i in range(10)})
print({i for i in range(10) if i%2 == 0})
# {变量(加工后的变量) for循环 加工条件}

python built-in functions usage

eval: type of code execution string, and returns the final result.

eval('2 + 2')  # 4
n=81
eval("n + 4")  # 85
eval('print(666)')  # 666

exec: execution string types.

s = '''
for i in [1,2,3]:
    print(i)
'''
exec(s)

Prohibit the use of two or more built-in functions very powerful work

hash: Get an object (the object may be a hash: int, str, Bool, tuple) hash value.

print(hash(12322))
print(hash('123'))
print(hash('arg'))
print(hash('alex'))
print(hash(True))
print(hash(False))
print(hash((1,2,3)))

'''
-2996001552409009098
-4637515981888139739
1
2528502973977326415
'''

help: function module or function for viewing purposes described in detail.

print(help(list))
print(help(str.split))

callable: function is used to check whether an object is callable. If it returns True, calls still may fail; but if it returns False, the calling object ojbect will never succeed.

name = 'alex'
def func():
    pass
print(callable(name))  # False
print(callable(func))  # True

int: function is used to convert a string or an integer number.

print(int())  # 0
print(int('12'))  # 12
print(int(3.6))  # 3
print(int('0100',base=2))  # 将2进制的 0100 转化成十进制。结果为 4

float: function is used to convert the integer to floating point and string.

complex: a function to create the complex value real + imag * j or transformed string or a plural number. If the first parameter is a string, there is no need to specify the second parameter. .

print(float(3))  # 3.0
print(complex(1,2))  # (1+2j)

bin: to convert decimal to binary and back.

oct: converted to decimal octal string and returns.

hex: decimal converted to a hexadecimal string and returns.

print(bin(10),type(bin(10)))  # 0b1010 <class 'str'>
print(oct(10),type(oct(10)))  # 0o12 <class 'str'>
print(hex(10),type(hex(10)))  # 0xa <class 'str'>

divmod: the divisor and the dividend calculation result, returns a tuple of the quotient and remainder of (a // b, a% b).

round: retention of floating-point decimal places, default retention integer.

pow: find the X- the y-th power. (Three parameters of x results of z I y taken)

print(divmod(7,2))  # (3, 1)
print(round(7/3,2))  # 2.33
print(round(7/3))  # 2
print(round(3.32567,3))  # 3.326
print(pow(2,3))  # 两个参数为2**3次幂
print(pow(2,3,3))  # 三个参数为2**3次幂,对3取余。

bytes: for conversion between different coding.

# s = '你好'
bs = s.encode('utf-8')
# print(bs)
s1 = bs.decode('utf-8')
# print(s1)
bs = bytes(s,encoding='utf-8')
# print(bs)
b = '你好'.encode('gbk')
# b1 = b.decode('gbk')
print(b1.encode('utf-8'))

ord: Enter the characters to find the character encoding of the current position

chr: enter the current position of the digital encoding to identify its corresponding character

# ord 输入字符找该字符编码的位置
print(ord('a'))
print(ord('中'))

# chr 输入位置数字找出其对应的字符
print(chr(97))
print(chr(20013))

repr: Returns a string form of the object (true colors).

# %r  原封不动的写出来
name = 'taibai'
print('我叫%r'%name)

# repr 原形毕露
print(repr('{"name":"alex"}'))
print('{"name":"alex"}')

all: iterables in all True is True

any: iterables, there is a True True

# all  可迭代对象中,全都是True才是True
# any  可迭代对象中,有一个True 就是True
print(all([1,2,True,0]))
print(any([1,'',0]))

Guess you like

Origin www.cnblogs.com/lifangzheng/p/11223714.html