Built-in and anonymous functions

Built-in function
1, basic data type
1, related to numbers
(1), number type: {
int: integer,
bool: boolean,
float: floating point,
complex: negative}
(2), base conversion {
bin: binary,
oct: octal,
hex: hexadecimal
}
(3), mathematical operations {
abs: absolute value,
divmod: return quotient,
round: decimal precision (default to integer, you can also mark the exact number of digits),
pow: Power operation,
sum: sum,
min: calculate the minimum value (you can pass a function in, or you can calculate an iterable object),
max: calculate the maximum value (always with the min method)
}
2. Related to data structure
(1), sequence {
lists and tuples: {list: convert to list, tuple: convert to tuple},
Related built-in functions: {reversed: the parameter is a sequence, the return value is a reverse iterator, slice: slice},
string: {
str: string,
format: formatted output (not just format, but also format_spec function ),
bytes: convert to bytes type,
bytearray: return a new byte array,
memoryview: return the memory view object of the given parameter,
ord: characters are converted to numbers
according to unicode chr: numbers are converted to characters according to unicode
ascii: strings are converted to ascii ,
repr: used for %r formatted output
}
(2), data set {
dict: dictionary,
set: set,
frozenset: returns a frozen set, after freezing, the set cannot add or delete any elements
}
(3), related Built-in function {
len: returns the length of an iterable object element,
enumerate: function is used to combine an iterable data object (such as a list, tuple or string) into an index sequence, \
lists both the data and the data under scalar, generally used in for loops,
all: determine whether there is a bool value of False,
any: determine whether there is a bool value of True,
zip: return an iterator
filter: receive a function f and a list list, this function f is used for the list Each element in the \
is judged, returns True or False, filter automatically filters out the elements that do not meet the conditions according to the result, returns \
returns the matching elements to form a new list,
map: The function is applied to each iterable item, the returned is a result list. If there are other iterable parameters passed to the
map function, each parameter will be iteratively processed with the corresponding processing function. The map() function receives two parameters, one is a function, and the
other is a sequence, map applies the incoming function to each element of the sequence in turn, and returns the result as a new list,
sorted: sorts list and Dict , return a copy, the original input remains unchanged (parameter description: iterable: iterable object; key: \
pass in a function name, the parameter of the function is each item in the iterable object, sorted according to the size of the return value of the function; reverse: Collation \
reverse=Ture descending, reverse=False ascending, there is a default value; return value: ordered list)
}
3. Scope related {
locals: return all local variables of the current position in dictionary type,
globals: return in dictionary type All global variables at the current location
}
4. Iterator\generator related {
range: function can create a list of integers, generally used in for loops,
next: return the next item of the iterator,
iter: used to generate the iterator
}
5. Other {
(1 ), the execution of string type code {
evel: used to execute a string expression and return the value of the expression
exec: used to execute a string expression, no return value
complie: encoding
}
(2), input and output {
input: input,
print: output,
}
(3), memory related {
hash: used to get the hash value of an object (string or value, etc.),
id: function used to get the memory address of the object
}
(4 ), file operation related {open: to open a file, create a file object, and related methods can call it to read and write}
(5), module related {__import__: used to dynamically load classes and functions}
(6), Help {help: enter help mode, specify to view help information for an object}
(7), call related: {callable: return True or False}
(8), view built-in attributes {dir: view all built-in functions (dir(__builtins__)), view
the attributes and methods of an object}
}
6, Object-oriented {
pass #I owe it first, I haven't learned it yet, I will add it later}
7. Reflection{}
}

Anonymous function
Anonymous function: a one-sentence function designed to solve the needs of those functions that are very simple
#this code
def calc(n):
    return n**n
print(calc(10))
 
#replace with anonymous function
calc = lambda n:n**n
print(calc(10))

 format description

function name = lambda parameters: return value
# There can be multiple parameters, separated by commas
#Anonymous function no matter how complicated the logic is, it can only write one line, and the content after the logic execution ends is the return value
#The return value can be any data type like a normal function

l=[3,2,100,999,213,1111,31121,333]
print(max(l))

dic={'k1':10,'k2':100,'k3':30}


print(max(dic))
print(dic[max(dic,key=lambda k:dic[k])])

  

res = map(lambda x:x**2,[1,5,7,4,8])
for i in res:
    print(i)

output
25
16

  

res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
    print(i)

output
15

  practise

There are two tuples (( ' a ' ),( ' b ' )),(( ' c ' ),( ' d ' )), please use an anonymous function in python to generate a list [{ ' a ' : ' c ' },{ ' b ' : ' d ' }]

#Answer 1 
test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]
 print (test(t1,t2))
 #Answer 2 
print (list(map( lambda t:{ t[0]:t[1 ]},zip(t1,t2))))
 #You can also write 
print ([{i:j} for i,j in zip(t1,t2)])
practise
1. The output of the following program is:
d = lambda p:p*2
t = lambda p:p*3
x = 2
x = d(x)
x = t(x)
x = d(x)
print x

2. Existing two-tuple (('a'), ('b')), (('c'), ('d')), please use the anonymous function in python to generate a list [{'a':' c'},{'b':'d'}]

3. What is the output of the following code? Please give an answer and explain.
def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])
Please modify the definition of multipliers to produce the desired result.

practise

 Mastering built-in functions

 

其他:input,print,type,hash,open,import,dir

 

Str type code execution: eval, exec

 

数字:bool,int,float,abs,divmod,min,max,sum,round,pow

 

Sequences - related to lists and tuples: list and tuple

 

sequence - string related: str, bytes, repr

 

Sequence: reversed, slice

 

Datasets - Dictionaries and Sets: dict, set, frozenset

 

Data collection: len, sorted, enumerate, zip, filter, map




Guess you like

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