Basic python content

Source: Internet
Author: User

Basic python content

1. Package

The import module name is first found in the current directory. In each module, you can use _ name _ to determine whether it is _ main _ to run the program to create a pack, create a folder, and then create _ init __. pyimport pack. filenamepack. filename. f ()
Reference package rename import pack as newnamefrom cal import * # in this way, you do not need to add the package name from sys import args # Only args does not need to add the package name
Pickle packages the object and saves it to the file out = open ("myindex. dat "," wb ") pickle. dump (myindex, out) # store a = pickle. load (out) # The pprint method in the pprint package can print objects visually.

2. File Operations
a=open('').readlines()
A [4] # Any location can be located
Len (open ('data. SQL '). readlines () # determine the number of rows
Read is to read all data into a string, readline is to read a row, readlines is to read all rows into a list, xreadlines is to read all rows, but when you use it, the data is read from the hard disk.

Fp. seek (offset [, whence]) to locate the offset. Fp. read ([size]) can provide an optional parameter size to specify the length of the read bytes.

From _ future _ import with_statementwith open ('/path/to/file', 'rb') as fp: for line in fp: do_something_with (line) # Faster

3. exist, traverse
There is an in operation.
When traversing a sequence in python, we usually use the following method: for item in sequence: process (item) If you want to get the position of an item, you can write it like this: for index in range (len (sequence): process (sequence [index]) Another better way is to use the python built-in enumerate function: enumerate (sequence, start = 0) in the above functions, sequence is an iteratable object, which can be a list, dictionary, and file object. The returned values of enumerate are tuples consisting of subscript and item: >>> seasons = ['spring', 'summer ', 'fall ', 'Winter '] >>> list (enumerate (seasons) [(0, 'spring'), (1, 'summer'), (2, 'fall '), (3, 'Winter ')] >>> list (enumerate (seasons, start = 1) [(1, 'spring'), (2, 'summer '), (3, 'fall'), (4, 'Winter ')] the first example can be written as follows: for index, item in enumerate (sequence ):

Print index, item

Which element index does you want to find? Which element has how many count added append insert, sort Delete pop (index) remove (ele)

For iterating_var in sequence:

Do

If the number range (I; j: Step Size) is closed before opening, the default value is 0. The default value is 1.

Xrange

For I (iterator) in "pathon" (sequence)

The iterator indicates that the content is not a subscript. If the lower mark is used, the for I int range (len () is used ()):

Traverse the dictionary for k, v in dict. items ():

Sum Len evaluate Length


Use of struct Arrays

Class item:

Def _ init _ (self ):

Self. name =''

Self. size = 10

Self. list = []

A = []

A. append (item ())

A [0]. name = 'cup'

A [0]. size = 8

Print len ()


Defines a with a length of 1000 and the initial value is 0.

a = [0 for x in range(0, 1000)]
Define a two-dimensional array
A = [[0 for x in range (10)] for y in range (10)]. If the length is longer, use a. append ([]).
for i in range(0, 10):    arraylist.append([])    for j in range(0, 5):        arraylist.append([])
4. Dictionary

Dictionary

Items () returns the tuples that contain key-value pairs.

Keys () values ()


5. Function usage
From sys import argv # package, that is, the module script, first, second, third = argv # script is the file name, followed by three parameters: print script, first, second, third

Basic functions use def print_two (* args): # if while for has a colon. Note that the pointer parameters are not the same as arg1, arg2, arg3 = argsprint "arg1: % r, arg2: % r, arg3: % r "% (arg1, arg2, arg3) print_two (" argument "," implument "," interface ") '''default parameter (from right to left). The global variable defined in the m (x = 3) function must be used after the function is called. If the duplicate name is used, the default return value is "None". The return value can be of any type and parameters can be transmitted using tuples. the return value function is used to transmit parameters as dictionaries '''
For multi-type data transfer, use the tuples f (* t) to pass the data in the tuples to the form parameters. If you need to transmit the corresponding values, use the dictionary f (** d) value Transfer redundancy def f (x, * args): args is a tuple def f (x, ** kword): Processing redundant dictionary parameter passing
6.
Lambda expressions
Lambda x, y: x * y return value of the left-side parameter of the colon
Reduce (f, l) applies function f to the following list reduce (lambda x, y: x * y, range )) the 720 dictionary also shows the effects of function pointers and switch. Dict = {'+': add, '-': sub}; dict ['+'] () use or dict. get ("+ ")()
7. Enter
Input raw_input () If you want other types, it is int (raw_input () raw_input ("your name ").


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.