New Python day 4 (appliance)

Keywords: Python JSON Lambda encoding

Python generator

Generators and build expressions

a=[i*2 for i in range(10)] generate expression
b=(i*2 for i in range(10)) (generator)

Features of generator: advantages (no memory space, fast generation speed), disadvantages (can't slice, can only save the current value, can't get the previous value)

Python create generator

#1.generator 
b=(i*2 for i in range(10))
#2.Function generator
def func(x):
    count=0
    while count<x:
        yield count  #Save the interrupt status of the current function(breakpoint)
        count += 1
f=func(10)

Methods of Python generator

print(f.__next__())#Call next element
print(f.send(1))#Send an element

Loop of Python generator

for i in (i*2 for i in range(10)):
    print(i)

Python iterator

Iteratable objects and iterators

Iteratable objects: objects that can be looped with for are all iteratable objects, such as list tuple dictionary strings
Iterator: objects with \

The transformation of Python iterator

#Iteratable objects become iterators
iter([1,2,3])

Python iterators and judgment of iterated objects

from collections import Iterable
from collections import Iterator
print(isinstance([1,2,3,4],Iterable))#Judge whether the object can be iterated
print(isinstance(iter([1,2,3,4]),Iterator))#Judge whether it is an iterator

Methods of Python iterator

print(iter([1,2,3]).__next__()) #Call next

Python iterator loop

for i in iter([1,2,3,4]):
    print(i)
#while Loop not recommended,Iterators are infinite and cannot compute the last value,Only with try To judge

Python built-in functions (judgment)

print(bool(1))#Boolean judgment
print(all([0,1,1]))#It's all true
print(any([0,1,1]))#One is true, the other is true
print(callable([]))#Is it a way,Is it possible to call

Python built-in functions (Transformations)

for i in enumerate(['a','b','c']):#Get subscript and content
    print(i)
print(bin(11))#Decimal to binary
print(oct(11))#Decimal to octal
print(hex(15))#Decimal to hexadecimal
bytes('a',encoding='utf-8')#Convert to binary format
tuple()  # List to tuple
frozenset([1,2,3,4])#Immutable set,Same as tuples
chr(99)#Return ascii Corresponding characters
float()#Convert floating point
repr(range(10))#Convert objects to strings
print(type(ascii([1,2,3])))#Become a string,It's no use
a=bytearray('abcd',encoding='utf-8')
a[0]=99#String and binary format cannot be modified,But this can be modified
print(a)

Python built-in functions (Computation)

print(pow(2,5))#Secondary power
print(abs(-1))#Calculate absolute value
print(divmod(5,2))#Return quotient and remainder
print(sum([1,2,3,4]))#Sum a list
round(1.2222,2)#Keep decimal places
print(max([1,2,3]))#Return maximum
print(min([1,2,3]))#Return minimum
for i in filter(lambda n:n<5,range(10)):#filter
    print(i)
for i in map(lambda n:n<5,range(10)):#Return to previous results
    print(i)

Python built in functions (view)

help()#Help
print()#Printing
print('{name}'.format(name='22'))#Format output
type('a')#View data types
print(dir({}))#View built-in methods
vars()#Returns all property names of an object
globals()#Print global variable's key and value
def func1():
    a=1
    print(locals())#Print all local variables
func1()

Python built-in functions (lists and iterators)

reversed([1,2,3])#Flip
print(sorted([2,1,3,4]))#sort
print(sorted({2:22,1:33,}.items()))#key sort
print(sorted({2:22,1:33,}.items(),key=lambda x:x[1]))#value sort
zip([1,2,3,4],['a','b','c','d'])#zipper
range(10)#An iterator from 0 to 10 excluding 10
next()#Used by iterators next Method
list=[1,2,3,4,5,6,7,8,9,10]
print(list[slice(2,5)])#It's no use slicing a class table

Python built-in functions (others)

#eval()#Executing simple code blocks
#exec()#Execute multiple code blocks
__import__('auth')#String import a module
#exit()#Sign out
#hash()#encryption
code='''for i in range(10)'''
#compile()#Compiling is useless
complex()#Plural not used
import functools
print(functools.reduce(lambda a,b:a+b,range(10)))#Summation
#super
#memoryview
#property
#credits()
#copyright()
#delattr()

Python json writing files (cross platform)

import json
data={'user':'admin','password':'000000'}
f_json=open('json.text','w')
#Write in json file
json.dump(data,f_json)
#f_json.write(json.dumps(data))
f_json.close()

Python json reading files

import json
f_json=open('json.text','r')
#json read file
load_json=json.load(f_json)
#load_json=json.loads(f_json.read())
f_json.close()

Python pickle write file (Python Limited)

import pickle
data={'user':'admin','password':'000000'}
f_pickle=open('pickle.text','wb')
#write file
pickle.dump(data,f_pickle)
#f_pickle.write(pickle.dumps(data))
f_pickle.close()

Python pickle reading files

import pickle
f_pickle=open('pickle.text','rb')
#read file
data_load_pickle=pickle.load(f_pickle)
#data_load_pickle=pickle.loads
f_pickle.close()

Posted by Warptweet on Sun, 03 May 2020 03:04:45 -0700