Built-in functions, anonymous functions

Built-in functions

  We take a look inside the python built-in functions. What is the built-in function? Python is provided to you, brought direct use of functions, such as print, input and so on. As of version 3.6.2 python, python now provides us with a total of 68 built-in functions . They are available to all python functions you can use directly used. Some of these functions we have used, and some we have not used before, and some are been sealed, so we have to learn new knowledge to unlock the seal. Well, today we get to know about the python's built-in functions. So many functions, we come to learn it?

 

     Built-in functions    
abs() dict() help() (I) setattr()
all()  to you()  hex()  next()  slice() 
any()  divmod ()  id()  object()  sorted() 
ascii() enumerate()  input()  oct()  staticmethod() 
bin()  eval()  int()  open()  str() 
bool()  exec()  isinstance()  words()  sum() 
bytearray()  filter()  issubclass()  pow()  super() 
bytes() float()  process ()  print()  tuple() 
callable() format()  Only ()  property()  type() 
chr() frozenset()  list()  range()  whose() 
classmethod()  getattr() locals()  repr()  zip() 
compile()  globals() map()  reversed()  __import__() 
complex()  Hsattr ()  max()  round()  
delattr() hash()  memoryview()  set()  

1.1 Scope-related

locals: function returns all of the local variables of the current location to the type dictionary.

globals: the type of function to return the entire dictionary of global variables.

. 1 = A
B = 2
Print (about locals ())
Print (Globals ())
# Like these two, because it is performed in the global.

##########################

def func(argv):
c = 2
print(locals())
print(globals())
func(3)

# These two are not the same, about locals () { 'the argv':. 3, 'C': 2}
#globals () { 'the __doc__': None, 'the __builtins__': <Module1 'the builtins' (Built-in)>, '__cached__': None, '__loader__ ': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__': None, '__file__': 'D: /lnh.python /.../ built-in functions .py', 'func' : <function func at 0x0000024408CF90D0>, '__name__': '__main__', '__package__': None}

The sample code

1.2 Other relevant

Eval 1.2.1 execution code string type, exec, complie

  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)

  compile: compiled code string type. Code objects can be executed by the exec statement or eval () is evaluated.

'' '
Parameters:   

1. Parameters source: string or AST (Abstract Syntax Trees) object. I.e. code segment need performed dynamically.  

2. Parameter filename: code file name, if not read the code from a file of the transfer of some recognizable value. When introduced to the source parameter, filename parameter passed to the null character.  

3. Parameter model: designating a type of compiled code, can be specified as 'exec', 'eval', 'single'. When the source is included in the process statement, model should be designated as 'exec'; when the source contains only a simple expression evaluation, model should be designated as 'eval'; when the source contains interactive command sentence, model specify It is a 'single'.
'' '
>>> # flow statement with Exec
>>> of code1 =' for I in Range (0,10): Print (I) '
>>> = compile1 the compile (of code1,' ',' Exec ')
>> > exec (compile1)


>>> # simple evaluation expression with the eval
>>> code2 = '. 1 + 2 + +. 4. 3'
>>> = compile2 the compile (code2, '', 'the eval')
>>> the eval (compile2)


>>> # interactive statement with SINGLE
>>> CODE3 = 'INPUT name = ( "Please INPUT your name:")'
>>> = compile3 the compile (CODE3, '', 'SINGLE')
>>> before executing name # variable name does not exist
Traceback (MOST Recent Last Call):
File "<pyshell # 29>", Line. 1, in <Module1>
name
NameError: name 'name' IS not defined
>>> Exec (compile3) is executed to display interactive # command prompt enter
please input your name: 'pythoner'
after execution name >>> name # variable has the value
" 'pythoner'"

Returns the value of the string of code with the eval, there is no return value of the code string with exec, generally do not compile.

1.2.2 O-related input, print

  input: a standard function accepts input data, return type string.

  print: print output.

'' 'Source code analysis
DEF Print (Self, * args, On Sep =', End = '\ n-', File = None): # Known Special Case of Print
"" "
Print (value, ..., On Sep = ' ', End =' \ n-', file = sys.stdout, the flush = False)
file: default output to the screen, if the settings as a file handle to a file
sep: separator between the plurality of print values, default space
end: the end of each print, the default is a newline
flush: immediately output to stream content file, without caching
"" "
'' '

print(111,222,333,sep='*') # 111*222*333

print (111, end = '' )
results in two rows of print (222) # 111222

Open = F ( 'log', 'W', encoding = 'UTF-. 8')
Print ( 'write file', file = f, flush = True)

1.2.3 memory-related hash id

  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
'''

  id: memory address for acquisition targets.

print(id(123))  # 1674055952
print(id('abc'))  # 2033192957072

1.2.3 file-related operations

  open: function is used to open a file, create a  file object associated method can invoke it to read and write.

1.2.4 Module-related __import__ 

  __import__: Function for dynamically loading classes and functions.

1.2.5 Help

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

print(help(list))
Help on class list in module builtins:

class list(object)
| list() -> new empty list
| list(iterable) -> new list initialized from iterable's items
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.n
|
| __ne__(self, value, /)
| Return self!=value.
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(...)
| L.__reversed__() -- return a reverse iterator over the list
|
| __rmul__(self, value, /)
| Return self*value.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(...)
| L.__sizeof__() -- size of L in memory, in bytes
|
| append(...)
| L.append(object) -> None -- append object to end
|
| clear(...)
| L.clear() -> None -- remove all items from L
|
| copy(...)
| L.copy() -> list -- a shallow copy of L
|
| count(...)
| L.count(value) -> integer -- return number of occurrences of value
|
| extend(...)
| L.extend(iterable) -> None -- extend list by appending elements from the iterable
|
| index(...)
| L.index(value, [start, [stop]]) -> integer -- return first index of value.
| Raises ValueError if the value is not present.
|
| insert(...)
| L.insert(index, object) -- insert object before index
|
| pop(...)
| L.pop([index]) -> item -- remove and return item at index (default last).
| Raises IndexError if list is empty or index is out of range.
|
| remove(...)
| L.remove(value) -> None -- remove first occurrence of value.
| Raises ValueError if the value is not present.
|
| reverse(...)
| L.reverse() -- reverse *IN PLACE*
|
| sort(...)
| L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE*
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __hash__ = None

None

Process finished with exit code 0

1.2.6 calls related

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

>>>callable(0)
False
>>> callable("runoob")
False

>>> def add(a, b):
... return a + b
...
>>> callable(add) # 函数返回 True
True
>>> class A: # 类
... def method(self):
... return 0
...
>>> callable(A) # 类返回 True
True
>>> a = A()
>>> callable(a) # 没有实现 __call__, 返回 False
False
>>> class B:
... def __call__(self):
... return 0
...
>>> callable(B)
True
>>> b = B()
>>> callable(b) # 实现 __call__, 返回 True

1.2.7 View built-in properties

  dir: When with no arguments, return variable in the current scope, and method of the type defined in the list; when arguments, and returns the parameter list of attributes and methods. If the parameter includes a method __dir __ (), which will be called. If the parameter does not contain __dir __ (), which will maximize the collection of parameter information.

>>> dir () # obtain a list of attributes for the current module
[ 'the __builtins__', 'the __doc__', 'the __name__', '__PACKAGE__', 'ARR', 'myslice']
>>> the dir ([]) to see a listing # The method of
[ '__add__', '__class__' , '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__ ',' __reduce__ ',' __reduce_ex__ ',' __repr__ ',' __reversed__ ',' __rmul__ ','__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

1.3 iterators generator related

  range: Integer object to create a function, generally used in a for loop.

  next: Internal actually used __next__ method that returns the next item in the iterator.

# First obtained Iterator objects:
IT = ITER ([. 1, 2,. 3,. 4,. 5])
# cycles:
the while True:
the try:
# get the next value:
X = Next (IT)
Print (X)
the except the StopIteration:
# encounter StopIteration loop exits
break

  iter: iterator function for generating (say an iterator object is generated iterator).

from collections import Iterable
from collections import Iterator
l = [1,2,3]
print(isinstance(l,Iterable)) # True
print(isinstance(l,Iterator)) # False

l1 = iter(l)
print(isinstance(l1,Iterable)) # True
print(isinstance(l1,Iterator)) # True

1.4 related to the underlying data type

1.4.1 digital correlator (14)

  

  Data type (4):

    bool: for a given parameter to a Boolean type, without parameters, return False.

    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)) # 0100 of the binary to decimal conversion. 4 results

    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. .

Complex >>> (. 1, 2)
(+ 2J. 1)

>>> Complex (. 1) # number
(+ 0j. 1)

>>> Complex ( ". 1") # treated as a string
(. 1 + 0j)

# Note: this place in the "+" number no spaces on either side, that is not written as "1 + 2j", should be "1 + 2j", otherwise it will error
>>> Complex ( "1 + 2j")
(1 + 2j)

 

  Base conversion (3):

    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'>

  

  Math (7):

    abs: absolute value function returns the number.

    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 x ** y power. (The result of the three parameters of x ** y I z taken)

print(abs(-5)) # 5

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 two parameters of power
print (pow (2,3,3)) # 2 ** three parameters of the third power, modulo 3 on.

    sum: summing calculation (can be set to an initial value) of iterables.

    min: returns the minimum iterator object (which can add key, key as the function name, the rule function returns the minimum value).

    max: returns the maximum iterator object (which can add key, key as the function name, the rule function returns the maximum value).

print(sum([1,2,3]))
print(sum((1,2,3),100))

print (min ([1,2,3])) # Returns the minimum sequence

ret = min ([1,2, -5 ,], key = abs) # according to the size of the absolute value, the sequence returns this minimum
print (ret)

dic = { 'A':. 3, 'B': 2, 'C':. 1}
Print (min (dic, Key = the lambda X: dic [X]))
# X is dic the key, lambda return value ( That value is compared dic) returns the minimum value of the key corresponding to


print (max ([1,2,3])) # Returns the maximum value of this sequence

ret = max ([1,2, -5 ,], key = abs) # according to the size of the absolute value, the sequence returns this maximum
print (ret)

dic = { 'A':. 3, 'B': 2, 'C':. 1}
Print (max (dic, Key = the lambda X: dic [X]))
# X is dic the key, lambda return value ( That value is compared dic) returns the key corresponding to the maximum value

1.4.2 and data structure (24)

  Lists and tuples (2)

    list: an iteration may be converted to the target list (if the dictionary, the key element as default list).

    tuple: The object is converted into an iterative tuples (if the dictionary, the default will be a key element tuples).

l = list((1,2,3))
print(l)

l = list({1,2,3})
print(l)

l = list({'k1':1,'k2':2})
print(l)

you = tuple ((1,2,3))
print (you)

you = tuple ([1,2,3])
print (you)

tu = tuple({'k1':1,'k2':2})
print(tu)

  Built-correlation function (2)

    reversed: a sequence inverted and inverted iterator returns this sequence.

    slice: construct a slice object for a list of sections.

ite = reversed(['a',2,3,'c',4,2])
for i in ite:
print(i)

li = [ 'a', 'b', 'c', 'd', 'e', 'f', 'g']
sli_obj = slice (3)
print (li [sli_obj])

sli_obj slice = (0,7,2)
print (li [sli_obj])

   Related string (9)

    str: the data into strings.

    format: related to specific data for calculating various decimal, actuarial.

# String parameters that may be provided, specify the alignment, <is left-aligned,> right-justified, centered ^ is
Print (the format ( 'Test', '<20 is'))
Print (the format (' Test ','> 20 is'))
Print (the format ( 'Test', '^ 20 is'))

# Shaping parameter values may be provided are 'B' 'C' 'D' 'O' 'X' 'X-' 'n-' None
>>> the format (. 3, 'B') # is converted into a binary
'11'
>> > format (97, 'c' ) # converted to unicode character
'A'
>>> the format (. 11, 'D') is converted to decimal #
'. 11'
>>> the format (. 11, 'O') # conversion 8 into binary
'13 is'
>>> the format (. 11, 'X') is converted into a hexadecimal # small letters
'B'
>>> the format (. 11, 'X-') # 16 is converted into capital letters hexadecimal
'B'
>>> the format (11, 'n-') and d # as
'11'
>>> the format (11), and d # as default
'11'

Floating-point parameters may be provided with a # 'E' 'E' 'F' 'F.' 'G' 'G' 'n-' '%' None
>>> the format (314 159 267, 'E') # scientific notation, the default reserved 6 decimal
'3.141593e + 08'
>>> the format (314 159 267, '0.2 e') # scientific notation, 2 decimal places designated
'3.14e + 08'
>>> the format (314 159 267, '0.2 e') # scientific notation to specify 2 decimal places, uppercase E represents
'3.14e + 08'
>>> the format (314 159 267, 'F') # decimal notation, a default retention six decimal places
'314,159,267.000000'
>>> the format ( 3.14159267000, 'f') # decimal notation, a default retention six decimal places
'3.141593'
>>> the format (3.14159267000, '0.8 F') # decimal notation, decimal 8 bits are designated
'3.14159267'
>>> the format (3.14159267000 , '0.10f') # decimal notation, decimal 10 specifies reserved
'3.1,415,926,700 '
>>> the format (3.14e + 1000000,' F. ') # Decimal notation, the size of the letter is converted into infinite
' INF '

#g special formatting, p is assumed that the format of decimal places specified, first try using scientific notation format, the exponent exp obtained, if -4 <= exp <p, is expressed in decimal notation, and reserved p-1-exp decimal, the decimal notation or counter press, press p-1 of decimal places
( '. 1g' 0.00003141566,) >>> format # p = 1, exp = -5 == "- 4 <= exp <p is not satisfied, counts the scientific notation, decimal 0 reserved
'3E-05'
>>> the format (0.00003141566, '. 2g') = P #. 1, -5 = exp == "-4 < = exp <p is not satisfied, the count by the scientific notation, a decimal reserved
'3.1E-05'
>>> the format (.00003141566, '. 3G') = P #. 1, -5 = exp == "-4 <= exp <p is not satisfied, according to scientific notation count decimal 2 reserved
'3.14e-05'
>>> the format (.00003141566, '. 3G') = P #. 1, -5 = exp == "-4 <= exp <p is not satisfied, counts the scientific notation, decimal 0 reserved, E uppercase
'3.14e-05'
>>> the format (3.1415926777, '. 1g') = P #. 1, 0 = exp == "-4 < = exp <p established by the decimal notation count decimal 0 reserved
'. 3'
>>> the format (3.1415926777,'.2g') # p = 1 , exp = 0 == "-4 <exp <p = established, according to decimal notation count, a decimal Reserved
'3.1'
>>> format (3.1415926777, '. 3g ') # p = 1, exp = 0 == "-4 <exp <p = established, according to decimal notation count decimal 2 Reserved
'3.14'
>>> the format ( 0.00003141566, '. 1n') # and g are the same
'3E-05'
>>> the format (0.00003141566, '. with 3N'), and g are the same #
'3.14e-05'
>>> the format (0.00003141566) and g are the same #
' 3.141566e-05 '

    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'))

    bytearry: Returns a new byte array. The array of elements is variable, and the range of values ​​for each element: 0 <= x <256.

K = ByteArray (Alex 'encoding =' UTF-8 ')
print (id (ref))
print (right)
print (right [0])
entitled [0] = 65
(printing right)
print (id (ref) )

    memoryview

ret = memoryview(bytes('你好',encoding='utf-8'))
print(len(ret))
print(ret)
print(bytes(ret[:3]).decode('utf-8'))
print(bytes(ret[3:]).decode('utf-8'))

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

    chr: Enter the numbers to find out the location of the corresponding character

    ascii: ascii code is returned to the value of not return / u ...

# Ord encoding input character to find the character position
# Print (the ord ( 'A'))
# Print (the ord ( 'in'))

# Chr input position to find out the number corresponding to the character
# Print (CHR (97))
# Print (CHR (20013))

The return value is # ascii codes, not on the return / U ...
# Print (ascii ( 'A'))
# Print (ascii ( 'in'))

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

#% R intact write
# name = 'Taibai'
# Print ( 'My name% r'% name)

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

  Data set (3)

    dict: create a dictionary.

    set: to create a collection.

    frozenset: Returns a frozen collection, the collection can not add or remove any elements after freezing.

  Built-correlation function (8)

     len: returns the number of elements in an object.

    sorted: Sort operation on all objects iteration.

 

L = [( 'A',. 1), ( 'C',. 3), ( 'D',. 4), ( 'B', 2),]
the sorted (L, Key = the lambda X: X [. 1]) # using Key
[( 'A',. 1), ( 'B', 2), ( 'C',. 3), ( 'D',. 4)]


Students. = [( 'John', 'A', 15) , ( 'Jane', 'B', 12 is), ( 'Dave', 'B', 10)]
the sorted (Students., Key = the lambda S: S [2]) # age sorting
[( 'dave', ' B ', 10), (' Jane ',' B ', 12 is), (' John ',' A ', 15)]

the sorted (Students., Key = the lambda S: S [2], Reverse = True) # press descending
[( 'john', 'A ', 15), ( 'jane', 'B', 12), ( 'dave', 'B', 10)]

    enumerate: enumeration, enumeration returns an object.

print(enumerate([1,2,3]))
for i in enumerate([1,2,3]):
    print(i)
for i in enumerate([1,2,3],100):
    print(i)

    all: iterables in all True is True

    any: iterables, there is a True True

Iterables # all in all is True True 
# iteration may be the any object, there is a True True 
# Print (All ([1,2, True, 0])) 
# Print (the any ([. 1, ' ', 0]))

     zip: object function is used as a parameter can be iterative, the corresponding element of the object packed into a tuple and returns a list of these tuples. If the number of elements of each iterator inconsistency, the shortest length of the list and returns the same objects.

l1 = [1,2,3,]
l2 = ['a','b','c',5]
l3 = ('*','**',(1,2,3))
for i in zip(l1,l2,l3):
    print(i)

    filter: · Filter.

#filter filtered through your function, an iterative filter object returns True
# similar to [I for I in Range (10) IF I>. 3]
# DEF FUNC (X): X return% 2 == 0
# filter = RET (FUNC, [1,2,3,4,5,6,7])
# Print (RET)
# for I in RET:
# Print (I)

    map: do mapping for the specified sequence according to the functions provided.

>>> def square (x): # calculate the number of squares
... return ** X 2
...
>>> Map (Square, [1,2,3,4,5]) # calculates the square of each element of the list
[1, 4, 9, 16, 25]
>>> Map (lambda X: X ** 2, [1, 2,. 3, 4,. 5]) using lambda # anonymous function
[1, 4, 9, 16, 25]

# two lists, a data list by adding the same position
>>> map (lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6 , 8, 10])
[3, 7, 11, 15, 19]

 Anonymous function

Anonymous function: function word function in order to solve those very simple needs and design.

Copy the code
# Code 
DEF Calc (n-): 
    return ** n-n- 
Print (Calc (10)) 
 
# anonymous function into 
Calc the lambda = n-: n-n-** 
Print (Calc (10))
Copy the code

The above is our analysis of the calc anonymous function, the following is a description of the anonymous function format

Name = lambda function parameter: Return value 

# parameter can have multiple, separated by commas 
# anonymous function no matter how complex logic, can only write a single line, and content after the end logic execution is the return value 
the function returns the # normal value and the same It can be any data type

We can see that anonymous function is not really can not have a name.

Calls and normal calls anonymous function is also no different. Is the function name (parameter) on it ~ ~ ~

Anonymous functions and built-in functions, for example:

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)
res = filter(lambda x:x>10,[5,8,11,9,15])
for i in res:
    print(i)
 

Guess you like

Origin www.cnblogs.com/Polar-sunshine/p/12446211.html