The python "turn" that I've been in for years.

Source: Internet
Author: User

The elements in the collection type are unique!

Definition and assignment of a collection:

1 set_1 = Set ([1, 3, 5, 7, 2]) 2 set_2 = Set ([2, 4, 6, 8, 3])

Operation Operations for collections

1 # intersection 2 print (set_1.intersection (set_2)) 3 # Set 4 print (Set_1.union (set_2)) 5 # Difference set 6 print (Set_1.difference (set_2)) 7 # Mutual The difference of the 8 print (Set_1.symmetric_difference (set_2)) 9 # No intersection decision of the print (Set_1.isdisjoint (set ([9,11])) 11 # Subset of the decision of the print (set ( [1,3]). Issubset (set_1)) 13 # Parent Set decision Print (Set_1.issuperset (set ([1,3]))

Collection of additions and deletions to change:

1 # intersection 2 print (set_1.intersection (set_2)) 3 # Set 4 print (Set_1.union (set_2)) 5 # Difference set 6 print (Set_1.difference (set_2)) 7 # Mutual The difference of the 8 print (Set_1.symmetric_difference (set_2)) 9 # No intersection decision of the print (Set_1.isdisjoint (set ([9,11])) 11 # Subset of the decision of the print (set ( [1,3]). Issubset (set_1)) 13 # Parent Set decision Print (Set_1.issuperset (set ([1,3])) 15 16 # add element: 17 # If the element already exists then do not change it. Set_1.add (3) print ( set_1) 20 21 # Change update: 22 # Merge and update set_1.update (set_2) 24 # Update the calculated results to the original collection set_1.difference_update (set_2)-set_1. Intersection_update (set_2) set_1.symmetric_difference_update (set_2) print (set_1) 29 30 # Delete element: 31 # If it doesn't exist, it won't be an error. set_ 1.discard (9) 33 # An error occurs when the element does not exist, compared to discard () Set_1.remove () 35 # Randomly deleting an element of Set_1.pop () 37 # Emptying the elements within the set Set_1.clear ()

Operation of the file

Path name access functions in the Os.path module

Separated

basename () Remove directory path, return file name

DirName () Remove file name, return directory path

Join () combines parts of the separation into one path name

Split () return (DirName (), basename ()) tuple

Splitdrive () return (drivename, pathname) tuple

Splitext () returns a tuple (filename filename, extension suffix)

Information

Getatime () returns the last access time

Getctime () returns file creation time

Getmtime () returns the last file modification time

GetSize () returns the file size (in bytes)

Inquire

Exists () specifies whether the path (file or directory) exists

Isabs () Specifies whether the path is an absolute path

Isdir () Specifies whether the path exists and is a directory

Isfile () Specifies whether the path exists and is a file

Islink () Specifies whether the path exists and is a symbolic link

Ismount () Specifies whether the path exists and is a mount point

Samefile () Two path names pointing to the same file

Os.path.isdir (name): Determine if Name is a directory, name is not a directory and return false

Os.path.isfile (name): Determine if name is not a file, does not exist name also returns false

Os.path.exists (name): Determine if there is a file or directory name

Os.path.getsize (name): Get file size, if name is directory return 0L

Os.path.abspath (name): Get absolute path

Os.path.normpath (PATH): Canonical path string form

Os.path.split (name): Split file name and directory (in fact, if you use the directory completely, it will also separate the last directory as the file name, and it will not determine whether the file or directory exists)

Os.path.splitext (): Detach file name and extension

Os.path.join (path,name): Connection directory with file name or directory

Os.path.basename (PATH): Return file name

Os.path.dirname (PATH): Return file path

File operations in the OS module:

1. Renaming: Os.rename (old, new)

2. Delete: Os.remove (file)

3. List files in directory: Os.listdir (PATH)

4. Get current working directory: OS.GETCWD ()

The built-in method of the file:
SN method to describe
1

File.close ()

Close the file. A closed file cannot read or write anything.
2

File.flush ()

Refreshes the internal cache, like the standard input fflush. This could be an empty operation for some class file objects.
3

File.fileno ()

Returns an integer file descriptor that is used by the underlying implementation, from operating system I/O operations.
4

File.isatty ()

Returns true if the file is connected to a TTY (like) device, otherwise false is returned.
5

Next (file)

Returns the next line in the file each time it is called.
6

File.read ([size])

Reads the size from the file up to bytes (or less if they get the size byte before the read hits EOF).
7

File.readline ([size])

Reads an entire line from the file. The end of the newline character remains in the string.
8

File.readlines ([Sizehint])

Read until EOF uses ReadLine () and returns a list containing the rows. If the optional sizehint parameter exists instead of reading to EOF, the total line amounts to about Sizehint bytes (which may be rounded to the internal buffer size) to be read.

9

File.seek (offset[, whence])

Set the current location of the file
10

File.tell ()

Returns the current location of the file
11

File.truncate ([size])

Truncates the size of the file. If the size parameter exists, the file is truncated to (at most) that size.

12

File.write (str)

Writes a string to the file. no return value.
13

File.writelines (Sequence)

Writes a string sequence to a file. The sequence can be a string of iterative objects-a typical string list.

Open File:

# do not need to close the file, the operation of the file all in the child code block to complete with open () as f:# the following way requires an explicit close file line F = open () f.close ()

The mode of opening the file is:

    • R, read-only mode (default).
    • W, write-only mode. "unreadable; not exist; create; delete content;"
    • A, append mode. "Readable; not exist" create; "only append content;"

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

    • r+, can read and write files. "readable; writable; can be added"
    • w+, write and read
    • A +, with a

"U" means that the \ r \ n \ r \ \ \ \ \ \ \ \ \ \ \ \ \ \ \ r or r+ mode can be converted automatically when reading

    • RU
    • R+u

"B" means processing binary files (e.g. FTP send upload ISO image file, Linux can be ignored, Windows process binary file should be labeled)

    • Rb
    • Wb
    • Ab

Read text file:

1 #后两个参数是默认的, can not add 2 input = open (' Data ', ' R ', encoding= ' utf-8 ')

Read binary files:

Read all file contents:

1 # Use in to get a line from a file 2 for lines in F:3      print (Line.strip ())

Read each line:

File_object.readlines () #不推荐 because it requires loading all of the file contents into memory, and if the file is particularly large, it has a big impact on performance!

Read Fixed bytes:

1 open (' abinfile ', ' RB '). Read (100)

Definition of the function:

1 # through Def and () define functions, () in the parameters of the function, define the function arguments as the form Parameter 2 # foo is the function of the logical code block 3 # return bar in the bar for the function return value 4 def func (Argument1,argument2 ...) : 5      foo6      return bar

Parameters of the function, the actual participation parameter:

The parameter name is defined in the time () of the function definition, and the argument refers to the actual parameter that is used when the function is called.

Positional, keyword, and non-fixed parameters for a function:

When calling a function to pass in a parameter, if you do not specify a keyword, the default is to pass in the order defined by the parameter, which is called the positional parameter;

1 func (1, ' xiaoming ')

When calling a function, you can use = to pass the value in according to the parameter name, which is called the keyword parameter;

1 func (id=1,name= ' xiaoming ')

There are two types of non-fixed parameters that are equivalent to the positional parameters of the *args, when defining parameters, adding a *args parameter to receive an unlimited number of arguments to facilitate the extension of the function.

1 def func (Name,*args): 2     Foo3 4 func (name= ' abc ', *[1,2,3,4])

The second is to use the **kwargs to identify, can receive the dictionary type of input, equivalent to the use of the number of keywords parameter is not fixed. Of course, both of these methods need to be identified using * or * * When the function is called.

1 def func (**kwargs) 2 3 func (**{' id ': 1, ' name ': ' Xiaoming '})

Arguments passed in principle: The keyword parameter cannot be placed before the positional parameter, not the fixed parameter at the end.

The return value of the function:

The return value of a function is a typical feature of programming, and the return value can be used to return the function's state, return the result of the function's processing, and invoke other functions, and of course the execution return represents the end of the whole process of the function.

1 def func (b): 2     if Foo:3         return A4     else:5         return b

Higher order functions:

1, the variable can point to the function;

2, the function of the return value can be a function;

3, one function can receive another function as a parameter;

1 def func (a,b,f): 2     return F (a) +f (b)

Recursive properties:

1. Must have a definite end condition

2, each time into a deeper level of recursion, the problem size should be reduced compared to the last recursion

3, recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, function calls through the stack (stack) This data structure implementation, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Because the size of the stack is not infinite, there are too many recursive calls, which can cause the stack to overflow.

Scope of the variable:

Variables can be divided into global variables and local variables, the definition of global variables is outside the function, or use the Global keyword to identify a variable.

As the name implies, the scope of the global variable is global, that is, any position after the variable definition position in the current PY file can be referenced by this variable.

A local variable is a variable that takes effect locally, such as a variable defined in a function that is valid within the function (except for the global identity), which is very different from the variables in the shell, and the variables in the shell are global variables, and if you want to identify local variables in the function, you need to use the keyword Local. It really is quite different.

Functional Programming:

Simply put, "functional programming" is a "programming paradigm" (programming paradigm), which is how to write a program's methodology. It belongs to "structured programming", the main idea is to write the operation process as far as possible as a series of nested function calls.

The python "turn" that I've been in for years.

Related Article

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.