Generators and built-in functions

one. Generator
 
There are three ways of generator:
 
1) Generator function
 
2) Data transformation
 


def generator():
    print(111)
    yield 222
    print(333)
    count = yield 444
    print(count)
    print(555)
    yield 666
g = generator()
print(g)
# print(list(g))
print(g. __next__())
print(g.__next__())
print(g.send('asd'))
print(list(g))
# Output result:
# <generator object generator at 0x0000017116671BF8>
# 111
# 222
# 333
# 444
# asd
# 555
# 666
# [] At this point, the generator function runs to the position of yield 666, so the conversion of g into a list is empty []

# If you just print print(list(g)) at the beginning -----> The output is completely different. The result is as follows:
# 111
# 333
# None
# 555
# [222, 444, 666]


3)
 
Comparing list comprehension and generator expression with generator expression:
 
list comprehension, generator expression
1) List comprehension is more intuitive and takes up memory
2) Generator expression is not easy to see the content and saves memory.
[variable (processed data) for variable i in iterable data type] list comprehension, loop pattern
[variable (processed data) for variable i in iterable data type if condition] list comprehension, filter pattern
 
list comprehension
 


# Print option 1, option 2. . . until option 10
li = ['option %s'%i for i in range(1,11)]
print(li)

# print all integers within 30 that are divisible by 4
l1 = [i for i in range(31) if i % 4 == 0]
print(l1)

# Swap keys in {'name':'alex','age':29} with their corresponding values
​​dic = {'name':'alex','age':29}
dict = {dic[i]: i for i in dic}
print(dict)

# Make a list with two e elements in it
names = [['Tom', 'Billy', 'Jefferson', 'Andrew', 'Wesley', 'Steven', 'Joe'],
         ['Alice' , 'Jill', 'Ana', 'Wendy', 'Jennifer', 'Sherry', 'Eva']]
l2 = [name for i in names for name in i if name.count('e') == 2 ]
print(l2)


generator expression
 


# print all integers within 30 that are divisible by 4
l1 = (i for i in range(31) if i % 4 == 0)
print(l1) #<generator object <genexpr> at 0x0000026AFA1E1BF8>
for i in l1:
    print (i)
#
# 0
# 4
# 8
# 12
# 16
# 20
# 24
# 28


 
 
two. Built-in functions Functions that
 
come with Python. such as range(), input(), len(), print(), dir(), max(), int(), min(), sum(), str(), list(), tuple(), id ()
 
1.
 


#print()
print('666',end='')
print('666')
# Output result: 666666
print(1,2,3,4,5,sep='|')
# Output result: 1| 2|3|4|5

# You can directly write the content you want to write to the file
f = open('file','w',encoding='utf-8')
print(666,file=f)
f.close()


2.
 
dir() finds all methods of an object
print(dir([]))
3.
 


locals() stores local variables
globals() stores global variables, function names, etc.
def func():
    name = 'alex'
    print(locals())
    print(globals())
func()


4.
 
help(str) Get all the information about the object you query.
5.
 


# abs() takes the absolute value
print(abs(-1))
# result: 1
def func(ret):
    print(44)
# maximum value
ret = max(1,2,-3,key=abs)
print(ret ) #-3
# #Minimum value
ret = min([1,2,3])
print(ret) #1
# #sum iterable, initial value
ret = sum([1,2,3],10)
print(ret ) #16


6.
 


#callable determines whether this variable is a function name
name = 'alex'
print(callable(name)) #False
def func():
    print(666)
print(callable(func)) #True


7.
 


#hash() Convert the object into a hash value through the rules of the hash table
print(hash('fdsakfhdsafsda'))
print(hash('fd'))
print(hash('fsdsafsda'))
print(hash(' fdsdsafsda'))
print(hash('dsakhdsafsda'))
print(hash(('a','b')))
print(hash(True))
# Output result:
# 1415579162147690152
# 5615420092049468879
# 46102622763726452226
#
-58803 9092531373745077475
# 1754971611771896552
# 1


8.
 
#all Convert all the values ​​in the iterable object into bool values ​​if all are True, return True
print(all([1,2,3,0])) #False
9.
 


#Convert decimal to binary
print(bin(100)) #0b1100100
# #Convert decimal to octal
print(oct(9)) #0o11
# #Convert decimal to hexadecimal
print(hex(33)) #0x21


10. #Data
 
type str()
#float: finite decimals, wireless cyclic decimals, not included (wireless non-circulating decimals)
print(1.35432,type(1.35432)) #1.35432 <class 'float'>
print(float(3)) #3.0
11.
 


complex()
'''
Real numbers: rational numbers, irrational numbers.
Imaginary numbers: j2
complex numbers: 1 + 2j
'''


12.
 
#divmod() paging
print(divmod(7,2)) #(3,1)(quotient, remainder)
13. Important
 


#enumerate(iterable,start start value) enumeration
l = ['mobile phone','phone','headphone',]
for i in enumerate(l):
    print(i)
# Output result:
# (0, 'Mobile phone' ')
# (1, 'Phone')
# (2, 'Headphone')
l = ['Phone', 'Phone', 'Headphone',]
for i,j in enumerate(l,100):
    print(i, j)
# output result:
# 100 phone
# 101 phone
# 102 headset


14.
 


#eval has a return value to remove the quotation marks on both sides of the string and returns the content inside
#exec No return value removes the quotation marks on both sides of the string and executes the code inside #Process statement
s = "{'name':'alex'}"
s1 = "1+2+3+4"
print(eval(s),type(eval(s))) #{'name': 'alex'} <class 'dict'>
print(exec(s),type(exec (s))) #None <class 'NoneType'>
print(eval(s1)) #10
code = '''for i in range(10):
    print(i)'''
print(exec(code)) # 0 1 2 3 4 5 6 7 8 9 None

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325768433&siteId=291194637