Python Foundation (set) supplement

Source: Internet
Author: User
Tags bit set chr iterable pow readline

1, the function parameter (reference) function's argument, passes the reference

def func (args): Args.appand (123) Li=[11,22,33]func (LI) print (LI) [11,22,33,123]

2.lambda expression

F4 (name of function) =LAMBDA parameter: Reture value

3. Built-in functions

1, Dict () Create a dictionary, list () Create lists, str () Create a string, tuple () create a tuple, floot () floating point, input () waits for user input,

round () rounding, Len () calculates the length (except integers), Max () max, min () minimum, print () printing, type () view type,

reversed () inversion, sum (objects that can be iterated) sum , Range () loop but not output,

2, ABS () take absolute value

A=abs ( -2) print (a) 2

3, all () loop parameter, returns True if each element is true, False if one element is False

If The iterable is empty, return True

True if there is only one empty in all

4, any () loop parameter, as long as one element is true, returns True

If the iterable is empty, return False

False if there is only one empty in any

5, ASCII () go to the input element of the class to find the __repr__ method, get its return value

Li=[]a=ascii (LI) print (a) []

6, Bin (number) binary representation

A=bin (6) print (a) 0b110

7. Oct () octal indicates

A=OCT (6) print (a) 0o6

8, int () decimal notation

A=int (6) print (a) 6

9, Hex () hexadecimal representation

A=hex (6) print (a) 0x6

10. Conversion between various systems

Other binary transfers are only one way Oct (other binary)

Other conversions are two ways int (other binary digits) or int ("Other binary digits", base= binary)

>>> Oct (x)

>>> Hex (x)

>>> Bin (x)

>>> Int (x)

>>>int (x,base=x)

A=hex (6) print (a) b=int ("0x6", base=16) print (b) 0x66

11, BOOL () to judge the true and false, to convert an object into a Boolean value

A Boolean value of false: [], {}, (), "", 0, None

A=bool ("") print (a) False

12, Bytes () byte ByteArray () byte list

Conversion between a string and a byte

#字符串转字节a=bytes ("Chinese", encoding= "Utf-8") print (a) B ' \xe4\xb8\xad\xe5\x9b\xbd\xe4\xba\xba '#字节转字符串 B=str (a,encoding= "Utf-8") print (b) Chinese

13. Chr () Converts the incoming number to the corresponding element in ASCII

A=CHR ($) print (a) B

14, Ord () converts the incoming element to the corresponding number in ASCII

A=ord ("a") print (a) 97

15, random a module, you can randomly produce an element

Import Randoma=random.randrange (65,90) print (a)

16. Verification Code

Import randomb= "" For I in range (6):    c=random.randrange (0,4)    if C==1 or c==3:        d=random.randrange (0,9)        B=b+str (d)    else:        a=random.randrange (65,80)        b=b+chr (a) print (b)

17, callable () check the resulting can be executed, the executable returns TRUE, otherwise returns false

def  F1 ()    reture 123a=callable (F1)
Print (a) True

18. Dir () View the methods in the object class Help ()

19, Divmod () is used to calculate the two numbers of division, and the quotient and the remainder of the meta-Zuzhong

A=divmod (10,3) print (a) (3, 1)

20, eval () can execute a string form of an expression (the string can only be a number)

A= "1+2" B=eval (a) print (b) 3

B=eval ("a+2", {"a": 1})  #eval后可以接收参数 (dictionary) to declare variable print (b) 3

21. EXEC () to execute. PY Code

EXEC ("For I in range (4):p rint (i)") 0123

22, filter (function, can be iterated) each of the parameters can be iterated into the function, if true to output the parameters, and vice versa to filter out

Def z (a):    if a>3:        return True    else:        return Falseret=filter (z,[1,2,3,4,5,]) print (ret) for I in RET:    print (i) <filter object at 0x0000001ea85b9550> #此处相当于range () does not directly output wasted memory 45
Def z (a):   return A+12ret=filter (z,[1,2,3,4,5,]) print (ret) for i in RET:    print (i) <filter object at 0x0000000f9ee49550>12345

23. Map (function, iterative) passes each parameter of the iteration into the function, executes the operation in the body of the function, and outputs the operation value

Def z (a):   return A+12ret=map (z,[1,2,3,4,5,]) print (ret) for i in RET:    print (i) <map object at 0x00000082dc909550>1314151617

24, Frozenset () a frozen set, cannot add elements

25, Global () to get the globals variable, and can change the global variable, locals () get local variable

Def z ():    name= "123"    Print (Globals ())    print (locals ()) Z () {' z ': <function z at 0x000000751d4eac80}{' Name ': ' 123 '}

26. Hash () to save the K value in the optimization dictionary

dict={"QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ": 1}a=hash ("QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ") print (a) 936761249792483134

27, Isinstannce () to determine whether the same class

Li=list () r=isinstance (li,list) print (R) True

28. ITER () creates an object that can iterate, removing a value when the iteration object executes next .

A=iter ([B1=next]) print (a) (a) print (B1) B2=next (a) print (B2) b3=next (a) print (B3) <list_iterator object at 0x0000005d5c239550>123

29. Pow () exponentiation

A=pow (2,10) print (a) 1024

30, Zip () will be several iterations of the type, according to the index position one by one corresponding combination

A=[1,2,3,4]b=[5,6,7,8]c= (1,2,3,4) d=zip (a,b,c) print (d) for i in D:    print (i) <zip object at 0x000000db794f0e88 > (1, 5, 1) (2, 6, 2) (3, 7, 3) (4, 8, 4)

**3 1. Sorted () Sorts objects (all of the same type) to get new values

A=[1,2,3,4,1212,13,4,56,7]b=a.sort () #执行sort方法Print (a) [1, 2, 3, 4, 4, 7, 13, 56, 1212]

1> Digital Sorting

A=[1,2,3,4,1212,13,4,56,7]b=sorted (a) #执行sort方法得到新值print (b) [1, 2, 3, 4, 4, 7, 13, 56, 1212]

2> String Sorting

char=[' Zhao ', ' 123 ', ' 1 ', ' + ', ' June ', ' 679999999999 ', ' a ', ' B ', ' Alex ', ' C ', ' a ', ' _ ', '? ', ' A money ', ' sun ', ' Li ', ' Yu ', ' di she ', ' Buddha ', '? ', "Iridium", " Zheng Zheng??? "] New_chat = sorted (char) print (new_chat) for I in New_chat:    print (bytes (i, encoding= ' utf-8 ')) [' 1 ', ' 123 ', ' 25 ', ' 65 ', ' 679999999999 ', ' a ', ' B ', ' _ ', ' A ', ' Alex ', ' A money ', ' C ', '? ', '? ', ' Sung ', ' di she ', ' Yu ', ' Sun ', ' Li ', ' Zhao ', ' Zheng Zheng??? ', ' Iridium ']b ' 1 ' b ' 123 ' B ' 25 '          B ' + ' B ' 679999999999 ' #字符串中是数字的按数字大小排序 (starting from the left first)B ' A ' B ' B ' B ' _ ' B ' A ' B ' Alex ' B ' a\xe9\x92\xb1 ' B ' C ' #大写的字母排到前面, lowercase in the back, see first bit (left first)B ' \xe1\x92\xb2 ' B ' \xe3\xbd\x99 ' B ' \xe4\xbd\x97 ' B ' \xe4\xbd\x98 ' B ' \xe4\xbd\ X99 ' B ' \xe5\xad\x99 ' B ' \xe6\x9d\x8e ' B ' \xe8\xb5\xb5 ' B ' \xe9\x92\xb2\xe9\x92\xb2\xe3\xbd\x99\xe3\xbd\x99\xe3\xbd\ X99 ' B ' \xe9\x93\xb1 ' #数字按照xe后跟的先排

 *** The open () function is used to process files

File handle = open (' File path ', ' mode ')

When you open a file, you need to specify the file path and how to open the file, open it, get the file handle, and later manipulate the file through this file handle

The mode of opening the file is:

 Basic operations

Normal open ()

A=open ("111.py", "R", encoding= "Utf-8") python must indicate the encoding method when it is opened in the R mode (the case of the text with Chinese characters)

    • R, read-only mode "default"
    • W, write-only mode "unreadable; not exist" created; empty content;
    • X, write-only mode "unreadable; not present, create, present error"
    • A, the Append mode is "unreadable; it is created if it does not exist; only the content is appended;

"B" means to operate in bytes

    • RB or R+b
    • WB or W+b
    • XB or W+b
    • AB or A+b

"+" means you can read and write a file at the same time

    • r+, read and write "readable, writable"
    • w+, write "readable, writable"
    • x+, write "readable, writable"
    • A +, write "readable, writable"

Seek (parameter) to adjust the pointer position

Tell () to get the pointer position

Read (parameter) plus arguments for reading the first few characters

r+ means readable, writable

Read and write: can read all the content, the pointer moves to the last side, append content after the content (regardless of the parameters in the read parameter is a few, then the pointer is written in the last, but then read the words are read in front of the pointer after the position as a starting point) ———————— before closing the file

A=open ("334.txt", "r+", encoding= "Utf-8") B=a.read () a.write ("FGH") A.close () print (b) 123

write after read: The pointer at the beginning of the position, write the contents of the previous overwrite, the pointer moved to the post-completion position, read the content after writing

A=open ("334.txt", "r+", encoding= "Utf-8") a.write ("FGH") C=a.read () A.close () print (c)

The w+ is emptied first, then the pointer is at the end, and the position of the pointer is adjusted using seek (parameter) to read

A=open ("334.txt", "w+") print (A.tell ()) A.write ("ASD") A.seek (0) B=a.read () A.close () print (b)

x+ with w+, error if file exists

A + opens while the pointer moves to the last

Read first and then write: At the beginning, the pointer will not read the content

Write first read: Append content after content, adjust pointer position can read to content

Operation

class file (object) def close (self): # real signature unknown;  Restored from __doc__ close file "" "Close () None or (perhaps) an integer.                 Close the file.  Sets data attribute. Closed to True.  A closed file cannot is used for further I/O operations.  Close () May is called more than once without error.        Some Kinds of File objects (for example, opened by Popen ()) could return an exit status upon closing. "" "Def Fileno (self): # real signature unknown;                 Restored from __doc__ file descriptor "" "Fileno (), integer" File descriptor ".        This is needed for Lower-level file interfaces, such Os.read (). "" "Return 0 def Flush (self): # real signature unknown;  Restored from __doc__ flush file internal buffer "" "Flush () None. Flush the internal I/O buffer. "" "Pass Def Isatty (self): # real signature unknown; Restored from __doc__ to determine if the file is a TTY device "" " Isatty () True or false. True if the file is connected to a TTY device. "" "Return False def Next (self): # real signature unknown; Restored from __doc__ gets the next row of data, does not exist, the error "" "" "" "" "" "" X.next (), the next value, or raise Stopiteration "" "p The Size=none (self, the): # Real signature unknown;                 Restored from __doc__ reads the specified byte data "" "Read ([size]), read at the most size bytes, returned as a string.        If the size argument is negative or omitted, read until EOF is reached.  Notice that while in non-blocking mode, less data than what is requested may be returned, even if no size parameter        was given. "" "Pass Def Readinto (self): # real signature unknown;  Restored from __doc__ read to buffer, do not use, will be abandoned "" "Readinto (), undocumented. Don ' t use this; It may go away. "" "Pass Def ReadLine (self, size=none): # Real signature unknown; Restored from __doc__ read only one row of data """ReadLine ([size]), next line from the file, as a string.  Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line is returned then)        .        Return an empty string at EOF. "" "Pass Def readlines (self, size=none): # Real signature unknown;  Restored from __doc__ reads all data and saves a list of values, "" "ReadLines ([size]), based on line break, and list of strings, each a lines from                 The file.        Call ReadLine () repeatedly and return a list of the lines so read.        The optional size argument, if given, is a approximate bound on the all number of bytes in the lines returned. "" "return [] def seek (self, offset, whence=none): # Real signature unknown;  Restored from __doc__ specifies the position of the pointer in the file "" "Seek (offset[, whence]), None.                 Move to new file position.  Argument offset is a byte count. Optional argument whence defaults to (offsEt from start of file, offset should is >= 0);  Other values is 1 (move relative to position, positive or negative), and 2 (move relative to end of  file, usually negative, although many platforms allow seeking beyond the end of a file).  If the file is opened in text mode, only offsets returned by tell () is legal.        Use of other offsets causes undefined behavior.        Note that not all file objects is seekable. "" "Pass Def Tell (self): # real signature unknown; Restored from __doc__ gets the current pointer position "", "Tell ()", "present file position, an integer (could be a long integer). "" "Pass def truncate (self, size=none): # Real signature unknown;  Restored from __doc__ truncates the data, leaving only the specified previous data "" "Truncate ([size]), None.                 Truncate the file to in the most size bytes.        Size defaults to the current file position, as returned by Tell (). "" "Pass Def write (self, p_str): #Real signature unknown;  Restored from __doc__ write content "" "Write (str)-None.                 Write string str to file.        Note that due to buffering, flush () or close () is needed before the file on disk reflects the data written. "" "Pass Def writelines (self, sequence_of_strings): # Real signature unknown;  Restored from __doc__ writes a list of strings to the file "" "Writelines (sequence_of_strings), None.                 Write the strings to the file.  Note that newlines is not added. The sequence can is any iterable object producing strings.        This is equivalent to calling write () for each string. "" "Pass Def Xreadlines (self): # real signature unknown;                 The restored from __doc__ can be used to read the file line by row, not all "" "Xreadlines ()-returns self. For backward compatibility.        File objects now include the performance optimizations previously implemented in the Xreadlines module.  """      Pass 

 

Class Textiowrapper (_textiobase): "" "Character and line based layer over a Bufferediobase object, buffer. Encoding gives the name of the encoding that the stream would be a decoded or encoded with.        It defaults to Locale.getpreferredencoding (False). Errors determines the strictness of encoding and decoding (see Help (Codecs.        CODEC) or the documentation for Codecs.register) and defaults to "strict". NewLine controls how line endings is handled.  It can be None, ', ' \ n ', ' \ R ', and ' \ r \ n '. It works as follows: * on input, if newline are None, universal newlines mode is enabled.      Lines in the input can end in ' \ n ', ' \ R ', or ' \ r \ n ', and these is translated into ' \ n ' before being returned to the Caller. If it is ", universal newline mode is enabled, but line endings was returned to the caller untranslated. If it has any of the other legal values, input lines is only terminated by the given string, and the line Endin G Is returned to the caller untranslated. * On output, if newline was None, any ' \ n ' characters written is translated to the system default line separator, OS. Linesep. If newline is ' or ' \ n ', no translation takes place.        If NewLine is any of the other legal values, any ' \ n ' characters written is translated to the given string.    If line_buffering is True, a call to flush was implied when a call to write contains a newline character. "" "Def Close (self, *args, **kwargs): # Real Signature unknown close file pass def fileno (self, *args, **kwa        RGS): # Real Signature Unknown file descriptor pass def flush (self, *args, **kwargs): # Real Signature Unknown Flush file Internal Buffer pass Def isatty (self, *args, **kwargs): # Real Signature Unknown determine if the file is consent to TTY device pas S def read (self, *args, **kwargs): # Real Signature Unknown read specified byte data pass def readable (self, *args, * *      Kwargs): # Real Signature Unknown  Readable pass def readline (self, *args, **kwargs): # Real Signature Unknown read only one row of data pass Def Seek (Self, *args, **kwargs): # Real signature Unknown specify pointer position in file pass Def seekable (self, *args, **kwargs): # r EAL signature Unknown pointer is operable pass DEF tell (self, *args, **kwargs): # Real signature unknown get pointer bit Set Pass Def truncate (self, *args, **kwargs): # Real Signature Unknown truncate data, retain only specified before data pass def WR Itable (self, *args, **kwargs): # Real Signature unknown can write pass def write (self, *args, **kwargs): # rea L Signature Unknown Write content pass def __getstate__ (self, *args, **kwargs): # Real signature unknown pas    S def __init__ (self, *args, **kwargs): # Real Signature Unknown pass @staticmethod # known case of __new__  def __new__ (*args, **kwargs): # Real signature Unknown "" "Create and return a new object. See Help (type) for accurate signature.    """    Pass Def __next__ (self, *args, **kwargs): # Real signature Unknown ' "" Implement Next (self). "" "        Pass Def __repr__ (self, *args, **kwargs): # Real signature Unknown ' "" Return repr (self). "" " Pass Buffer = Property (Lambda self:object (), Lambda Self, v:none, lambda Self:none) # Default closed = Property ( Lambda Self:object (), Lambda Self, v:none, lambda self:none) # Default encoding = property (Lambda self:object (), L Ambda self, V:none, lambda self:none) # Default Errors = Property (Lambda self:object (), Lambda Self, v:none, LAMBD A self:none) # Default Line_buffering = Property (Lambda self:object (), Lambda Self, v:none, Lambda Self:none) # D Efault Name = Property (Lambda self:object (), Lambda Self, v:none, lambda self:none) # default newlines = Propert Y (Lambda self:object (), Lambda Self, v:none, lambda self:none) # Default _chunk_size = Property (Lambda self:object (), Lambda Self, v:none, lambda self:None) # Default _finalizing = Property (Lambda self:object (), Lambda Self, v:none, lambda self:none) # Default 

Flush (self): flush the file internal buffer

If the process does not end (with input ("SSSs"), the contents of write ("Assds") are not brushed to the hard disk, cannot be read, plus the LOC Shou flush () will be able to force the content to be brushed to the hard disk, not end the process can also read

Read (parameters):

All content is read without parameters, plus the parameter means reading several characters (opened in R) or several bytes (open in RB mode)

ReadLine (): Read only one row of data

Truncate (self, *args, **kwargs): truncates data, retains only  the position specified before the data depends on the pointer a=open ("334.txt", "r+") print (A.tell ()) Print (A.seek (5)) A.truncate () A.close () 0 5 #用于截取文件内容中前五个字符串的内容

F=open ("111.py", "r+", encoding= "Utf-8")  #f是可以循环的 for  line  in F:print (line) #可以把内容一行一行的读出来, you can see the contents of the Last line

Management context

To avoid forgetting to close a file after opening it, you can manage the context by:

With  open ("xxx", "xx", encoding= "Utf-8") as F:    Pass

This way, when the with code block finishes executing, the internal automatically shuts down and frees the file resource.

In Python 2.7 and later, with also supports the management of multiple file contexts simultaneously, namely:

With open (' Log1 ') as Obj1, open (' log2 ') as Obj2:    Pass

Python Foundation (set) supplement

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.