0517Python Basics-built-in functions

Source: Internet
Author: User
Tags decimal to binary ord pow

1. Yesterday's content review

An iterative object: An internally containing __iter__ method

Iterators: Internally containing the __iter__ method and also containing the __next__ method

An iterative object. __iter__ ()

Determines the iterator that iterates over an object.

' __iter__ ' in Dir (iterative object)

' __next__ ' in Dir (iterative object)

Isinstance (obj, Iterator)

Isinstance (obj, iterable)

Iterators:

Save memory.

Inertia mechanism.

Unidirectional irreversible.

Generator:

The generator is essentially an iterator, which is written in Python code.

The generator function. Yield

__next__ Send ()

Generator derivation.

[Variable (processed variable) for variable in iteration Object] traversal mode.

[Variable (post-processed variable) for variable in can iterate object if condition] Filter mode.

() Generator derivation

2. Built-in functions

Key memory

Using domain-related

**globals () returns a global variable in the form of a dictionary

**locals () A local variable that returns the current position in the form of a dictionary

Q = 666

def wrapper (argv):

A = 3

Print (Locals ()) # 1 {a:3,argv:2}

def inner (ARGV1):

b = 4

c = 5

Print (Locals ()) # 2 {b:4 C:5,argv1:6}

Inner (6)

Wrapper (2)

Print (Globals ()) # 3

Other related

1.2.1 Execution of String type code Eval,exec,complie

Eval removes quotation marks from a string, returns the corresponding internal value

s = ' {' A ': 1, ' B ': 3} '

DIC = eval (s)

Print (Dic,type (DIC))

Print (eval (' 2 + 2 '))

Print (eval (' Print (666) '))

EXEC executes code inside the string

Print (EXEC (' 1 + 1 '))

ret = "'

Name = input (' Please enter name: '). Strip ()

If name = = ' Alex ':

Print (666)

‘‘‘

EXEC (ret)

Compile:pass

1.2.2 Input/output related Input,print

Name = input (' Please%s enter name: '% ' Alex ')

Print (name)

Print (1, 2, 3,sep= ' * ') # Sets the way the printing element is connected

Print (' Alex ', end= ') # End controls the line break

Print (' Old boy ')

F1 = open (' Log ', encoding= ' utf-8 ', mode= ' W ')

Print (' 666 ', file=f1) # file handle, write file.

F1.close ()

1.2.3 memory-related hash ID

*hash converts immutable data to hash value via hash algorithm

Print (hash (' name '))

Print (hash (' age '))

Print (Hash ((1, 2, 3,))

Print (hash (1))

Print (hash (100))

*print (ID (' name '))

1.2.3 File Operation related

The Open: function opens a file, creates a Files object, and the associated method can call it for read and write.

1.2.4 Module Related __import__

__IMPORT__: Functions are used to dynamically load classes and functions.

1.2.5 Help

*help: The function is used to view a detailed description of the function or module's purpose.

Print (Help (str))

1.2.6 Call Related

Callable: The function is used to check whether an object is callable.

If return true,object still may fail, but if return false, calling object Ojbect will never succeed.

Def func1 ():

Print (666)

Age = 16

Print (Callable (' name '))

Print (callable (age))

Print (callable (FUNC1))

1.2.7 view built-in properties

* * dir: Returns a list of variables, methods, and definitions in the current scope when the function has no arguments;

With parameters, returns the properties of the parameter, a list of methods. If the parameter contains method __dir__ (), the method is called.

If the parameter does not contain __dir__ (), the method will collect the parameter information to the fullest extent.

Print (dir (str))

1.3 Iterator Generator related

Range Iter () next ()

Print (Len (range (100)))

L = [1, 2, 3, 4, 5]

L_obj = l.__iter__ ()

L_obj = iter (l)

Print (L_obj)

Print (l_obj.__next__ ())

Print (Next (l_obj))

1.4.1 Digital Correlation (14)

Data type (4):

BOOL: Used to convert the given parameter to a Boolean type, or False if there are no arguments.

int: function is used to convert a string or number to an integral type.

print (int (' 123 '))

Print (int (1.234))

Print (int (1.768))

The float: function is used to convert integers and strings into floating-point numbers.

Complex: The function is used to create a complex number with a value of real + Imag * J or to convert a string or plural.

If the first argument is a string, you do not need to specify a second parameter:

i = 3.1415

Print (I, type (i))

s = ' 1.234 '

Print (int (1.234))

Print (float (s))

Print (float (100))

Bin: Converts decimal to binary and returns.

Print (Bin (100))

Oct: Converts decimal into octal string and returns.

Print (Oct (10))

Hex: Converts decimal into a hexadecimal string and returns.

Print (Hex (13))

Print (Hex (18))

Mathematical Operations (7):

**abs: The function returns the absolute value of the number.

Print (ABS (-5))

Divmod: Calculates the result of divisor and divisor, returns a tuple containing quotient and remainder (A//b, a% b).

Print (Divmod (7, 3))

**round: Preserves the number of decimal digits for floating-point numbers, and preserves integers by default.

Print (Round (1.234,2))

*pow: Seek x**y power. (Three parameters for the result of X**y to Z-redundancy)

Print (POW (2, 3)) # 2 three power

Print (POW (2, 3, 3)) # 2 three power to 3 take remainder

Sum: Computes the sum of the objects that can be iterated (the initial values can be set).

Print (sum ([1, 2, 3, 4])

Print (sum ([1, 2, 3, 4], 100))

Min: Returns the minimum value of the object that can be iterated (Key,key is the function name, and the minimum value is returned by the rule of the function).

Print (min ([1, 3, 5, 7,-4]))

Print (min ([1, 3, 5, 7,-4], key=abs))

Max: Returns the maximum value of an object that can be iterated (Key,key is the function name, and the maximum value is returned by the rule of the function).

Print (max ([1, 3, 5, 7,-4]))

Print (max ([1, 3, 5, 7,-9], key=abs))

1.4.2 and data structure related (24)

Lists and Ganso (2)

List: Converts an iterative object to a list (in the case of a dictionary, by default the key is the element of the list).

Tuple: Converts an iterative object into Cheng Yuanju (in the case of a dictionary, the key is the Ganso element by default).

Tu = (1, 2, 3)

Print (List (TU))

L1 = List ((1, 2, 3))

L1 = List ({' Name ': ' Alex ', ' Age ': 1000})

Print (L1)

Try it Yourself

Related built-in functions (2)

Reversed: Flips a sequence and returns an iterator for this flip sequence.

L1 = [11, 22, 33, 44, 77, 66]

L_obj = reversed (L1)

# Print (l_obj)

For I in L_obj:

Print (i)

Slice: Constructs a slice object that is used for the slice of the list.

L1 = [11, 22, 33, 44, 77, 66]

L2 = [111, 222, 333, 444, 777, 666]

# print (L1[1::2])

Rule = Slice (1, Len (L2), 2)

Print (L2[rule])

String Correlation (9)

STR: Converts data into a string.

Format: related to specific data, used to calculate various decimals, actuarial, etc.

Print (Format (' Test ', ' <20 ')) # left Justified

Print (Format (' Test ', ' >20 ')) # Right-aligned

Print (Format (' Test ', ' ^20 ')) # centered

Bytes:str---> bytes

S1 = ' Alex '

# B1 = S1.encode (' Utf-8 ')

b2 = bytes (s1,encoding= ' Utf-8 ')

# Print (B1)

Print (B2)

ByteArray

ret = ByteArray (' Alex ', encoding= ' utf-8 ') # analogy: [97,103,....]

Print (the ID (ret))

Print (ret) # ByteArray (b ' Alex ')

Print (Ret[0])

Ret[0] = 65

Print (ret)

Print (the ID (ret))

bytes to convert to Str

B1 = bytes (' Hello ', encoding= ' utf-8 ')

Print (B1)

ret = Memoryview (B1)

# print (len (ret))

# Print (ret)

Print (bytes (Ret[:3]). Decode (' Utf-8 '))

Print (bytes (ret[3:]). Decode (' Utf-8 '))

Ord: Enter the character to find the location of the character encoding

Print (Ord (' A '))

Print (Ord (' Middle ')) # Unicode

CHR: Enter a position number to find its corresponding character

Print (Chr (65))

Print (Chr (20013)) # Unicode

ASCII: Is the value returned in ASCII code, not just return u/s ...

Print (ASCII (' a '))

Print (ASCII (1))

Print (ASCII (' Medium '))

Repr: Returns the string form of an object (the True colors).

msg = ' Fractional%f '% (1.234)

Print (msg)

msg = ' name:%r '% (' Alex ')

Print (msg)

Print (repr (' {' name ': ' Alex '} '))

Print (' {' name ': ' Alex '} ')

Data sets (3)

Dict: Create a dictionary.

Set: Creates a collection.

Frozenset: Returns a frozen collection that freezes after the collection can no longer add or remove any elements.

DIC = Dict ({' name ': ' Alex '})

Print (DIC)

Set1 = Set (' Alex ', ' Wusir ')

Print (SET1)

Related built-in functions (8)

Len: Returns the number of elements in an object.

Sorted: Sorts all objects that can be iterated. Returned is the list

Print (sorted ([1, 2, 3, 4, 5,-6]))

Print (sorted ([1, 2, 3, 4, 5,-6], key=abs))

L = [(' A ', 1), (' C ', 2), (' d ', 4), (' B ', 3),]

Print (sorted (L))

def func1 (x):

return x[1]

L = [(' A ', 1), (' C ', 2), (' d ', 4), (' B ', 3),]

Print (sorted (L, KEY=FUNC1))

*all: Can iterate over objects, all true is true

*any: Can iterate over objects, with a true is true

Print (All ([1, ' Alex ', True, (+)]))

Print (All ([0, ' Alex ', True, (+)]))

Print (Any ([0, ', False, (+)]))

Print (Any ([0, ', False, ()]))

The zip Zip method returns an iterator

L1 = [1, 2, 3, 4]

TU1 = (' Old boy ', ' Alex ', ' Wusir ')

L2 = [' * ', ' * * ', ' * * * ', ' * * * *]

obj = Zip (l1,tu1,l2)

For i in obj:

Print (i)

Map: Loop mode

def func2 (x):

Return x**2

obj = Map (Func2, [1, 2, 3, 4])

For i in obj:

Print (i)

Print ((i**2 for I in [1, 2, 3, 4]))

def func2 (x, y):

return x + y

obj1 = Map (Func2, [1, 2, 3, 4, 6], (2, 3, 4, 5))

For I in Obj1:

Print (i)

Filter filtering mode

def func (x):

return x% 2 = = 0

RET = Filter (func,[1, 2, 3, 4, 5, 6, 7])

Print (ret)

For I in RET:

Print (i)

Print ((i-I in [1, 2, 3, 4, 5, 6, 7] if I% 2 = = 0))

Lambda anonymous function one sentence function

def func (x): return x% 2 = = 0

def func1 (x, y):

return x + y

ret = lambda x, y:x+y

Print (ret (2,3))

def func1 (x, y):

return x if x > y else y

ret = lambda x, y:x if x > y else y

Print (ret (2,3))

def func (x):

return x% 2 = = 0

RET = filter (lambda x:x% 2 = = 0, [1, 2, 3, 4, 5, 6, 7])

Print (ret)

For I in RET:

Print (i)

[1, 2, 3, 4, 5, 6, 7] [1,4,9,16 ...] map lambda

Ret2 = map (lambda x:x**2,[1, 2, 3, 4, 5, 6, 7])

For I in Ret2:

Print (i)

def func1 (x):

return x[1]

L = [(' A ', 1), (' C ', 2), (' d ', 4), (' B ', 3),]

Print (sorted (L, KEY=FUNC1))

Students = [(' John ', ' A ', '), (' Jane ', ' B ', '), (' Dave ', ' B ', 10)]

L = sorted (students, key= Lambda x:x[2],reverse=true)

Print (L)

Sorted Max min Map filter

0517Python Basics-built-in functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.