Built-in Functions and Anonymous Functions
Keywords:
Python
Lambda
encoding
ascii
python provides powerful built-in functions, so let's take a look at what these functions do.
Absolute value of abs().
print(abs(-1))
print(abs(0))
Operation result
1
0
abs
all() passes on an iteratable object, each worth bool value of which returns Ture for Ture, one for False, and the result for False.
print(all(i for i in range(10)))#False
print(all(i for i in range(1,10)))#True
all()
sum() converts an object into an iterative object sum.
res=sum(i for i in range(3))
print(res)#3
sum()
any() passes on an iteratable object, in which a bool value of one value is Ture to return Ture, all values are False, and the result is False.
print(any([]))#False
print(any([None,0,'',{},1]))#True
any()
bin() converts the incoming value into binary.
print(bin(3))#0b11
bin()
bool() returns the bool value.
print(bool(0))#False
print(bool(None))#False
print(bool(''))#False
bool()
bytes() converts a string to byte mode.
print(bytes('hello',encoding='utf-8'))#b'hello'
bytes()
Whether callable() can be invoked returns the bool value.
def test():
pass
print(callable(test))#True
print(callable(sum))#True
callable()
The corresponding relationship between chr() and ord()ASCII codes.
print(chr(67))#C
print(chr(65))#A
print(ord('A'))#65
chr()ord()
Class method, static method, property object-oriented three bitch.
classmethod
class people:
country = 'china'
# Class method, using classmethod To decorate
@classmethod
def getCountry(cls): #Class methods automatically treat classes as cls Transfer into function
return cls.country
@classmethod
def setCountry(cls, country):
cls.country = country
p = people()
print(p.getCountry()) # You can use instance object references
print(people.getCountry()) # References can be made through class objects
p.setCountry('japan')
print(p.getCountry())
//Operation results:
china
china
japan
classmethod
staticmethod
class people:
country = 'china'
@staticmethod
# Static methods are bound in a decorator fashion and, like ordinary functions, are not automatically passed on self
def getCountry():
return people.country
print(people.getCountry())
//Operation results:
china
staticmethod
property
class people:
__name = 'jeff'
__age = 12
def set(self):
print(self.__name)
print(self.__age)
p = people()
#print(p.__name,p.__age) #AttributeError: 'people' object has no attribute '__name'
p.set()
//Operation results;
jeff
12
property
complex() Complex, defining complex
x=complex(1-2j)
print(x.real)#1.0
print(x.imag)#-2.0
x=1-2j
print(x.real)#1.0
print(x.imag)#-2.0
complex()
Data type
int() integer, isinstance() to determine the data type
num=1 #num=int(1)
print(type(num)) #See num Types<class 'int'>
print(isinstance(num,int)) #judge num Whether it is int type True
print(num is 1) #is Identity arithmetic, based on id To judge identity Tr
int()isinstance()
float() converts numbers into floating-point types.
str() is converted to a string.
list() converts any iterable into a list.
x=list(i for i in range(10))
print(x)#[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
list()
tuple() is converted into tuples.
dict()
d={'a':1}
d=dict(x=1,y=2,z=3)
print(d)#{'z': 3, 'x': 1, 'y': 2}
dict()
set() is transformed into a set, which is an iterative object and a list.
frozenset() immutable set
s={1,2,3,4,4}
print(s)
s.add(5)
print(s)#set Incremental but immutable sets are not allowed
f=frozenset({1,2,3,4})
print(type(f))
frozenset()
What callable methods are there under the dir() object?
Dimod () returns tuples (x//y, x%y), front-end paging.
print(divmod(100,33))#(3, 1)
divmod()
enumerate() iterator
for i in enumerate(['a','b','c','d']):
print(i)
//Operation results:
(0, 'a')
(1, 'b')
(2, 'c')
(3, 'd')
for i in enumerate({'x':1,'y':2}):
print(i)
//Operation results:
(0, 'y')
(1, 'x')
enumerate()
format() formatted output
globals() gets the dictionary of global variables and locals() gets the dictionary of local variables in the namespace where the method is executed.
def func():
x = 1
y = 2
print(locals()) #Print names in local scope
print(globals()) #Print names in global scope
globals()locals()
hash() gets the hash value, which is used to verify the integrity of the data and is irreversible.
s='hello'
print(hash(s))#-6379790348615061731
s='h'
print(hash(s))#5735203904575971755
hash()
help() Get help.
hex() to hexadecimal
print(hex(10))#0xa
print(hex(11))#0xb
hex()
If id() looks at the unique id number, is is to determine whether the id is the same.
print(id('asdf'))
a=1
b=2
print(id(a))
print(id(b))
print(a is b)
x='a'
y='a'
print(id(x))
print(id(y))
print(x is y)
id()
input() input
iter() converts an iterative object into an iterator.
len() Statistical Length
max(),min() maximum and minimum
zip() zipper function? zip converts the two incoming parameters into iteratable objects, with next() on each side being placed in a tuple.
l1=[1,2,3,4]
s='hel'
for i in zip(l1,s):
print(i)
//Operation results:
(1, 'h')
(2, 'e')
(3, 'l')
zip()
sorted() next the iteratable object once and then ascend to the list.
l=[3,4,1,0,9,10]
print(sorted(l)) #The return value is a list and the default is ascending order
print(sorted(l,reverse=True)) #Descending order
sorted()
map() mapping. Each number on the right maps a new list according to the rules on the left.
l=[1,2,3,7,5]
m=map(lambda item:item**2,l)
print(m)#<map object at 0x00000000027CDD68>
print(list(m))#print(list(m))
map()
from functools import reduce merge
from functools import reduce #merge
l=list(range(100))
print(l)
print(reduce(lambda x,y:x+y,l,100))#5050#Reduc can pass multiple values
from functools import reduce
filter filtering
name_l=[
{'name':'egon','age':18},
{'name':'dragonFire','age':1000},
{'name':'gaoluchuan','age':9000},
{'name':'fsw','age':10000},
]
f=filter(lambda d:d['age'] > 100,name_l)#Return value on the left ture filter out
print(list(f))#[{'name': 'dragonFire', 'age': 1000}, {'name': 'gaoluchuan', 'age': 9000}, {'name': 'fsw', 'age': 10000}]
filter
oct() octal
open() Gets the file handle
pow(x,y,z),x**y%z
range() to obtain iterative objects
rper() also shows that str is more humane
reversed() inversion order
slice() slices, which are not usually used
vars() returns the name of the local namespace in dictionary form.
_ import_ Imports strings
__import__('time')
__import__
Compoile () compiles strings into bytecodes and runs.
Exc () executes code or compiled string without return value
eval() converts an expression in a string to a python expression with a return value
round(x,[,n]) rounds off the value of x, n denotes decimal points.
Anonymous function
Comparing the salaries of several teachers, who gets the highest salary?
salaries={
'egon':3000,
'alex':100000000,
'wupeiqi':10000,
'yuanhao':250
}
max() is used directly to get the maximum value of the key, and value is used to get the most money. How to compare money and get the corresponding key of the money?
def get_value(k):
return salaries[k]
print(max(salaries,key=get_value))#alex
Here, max transforms the incoming value into an iterative object, takes one value at a time and passes it to the function on the right, then compares it, and finally comes to the person whose maximum value is output to the maximum value.
The get_value function we defined here is very simple. It has only a single function and is completely unnecessary. We can use a simple lambda to complete it step by step.
lambda k:salaries[k]
Call of anonymous functions.
f=lambda k:salaries[k] #Anonymous functions can also assign a name, but this violates the original intention of anonymity.
print(f)#<function <lambda> at 0x0000000001D0CBF8>
print(f('egon'))#3000
It is also easier to solve the above problems.
print(max(salaries,key=lambda k:salaries[k]))#alex
print(min(salaries,key=lambda k:salaries[k]))#yuanhao
zip() function
print(salaries.keys(),salaries.values())
z=zip(salaries.values(),salaries.keys())
print(z)
print(max(z))#Take out the largest tuple
for i in z:
print(i)
sorted()
print(sorted(salaries)) #The default is to follow the dictionary salaries Of key Sorted
print(sorted(salaries,key=lambda x:salaries[x]))
print(sorted(salaries,key=lambda x:salaries[x],reverse=True))
//Operation results:
['alex', 'egon', 'wupeiqi', 'yuanhao']
['yuanhao', 'egon', 'wupeiqi', 'alex']
['alex', 'wupeiqi', 'egon', 'yuanhao']
Posted by phpnoobie9 on Mon, 27 May 2019 11:39:55 -0700