Python Foundation case

Source: Internet
Author: User
Tags vars python list

Example one:

Exercise: Element classification

There is a collection of the following values [11,22,33,44,55,66,77,88,99,90 ...], saving all values greater than 66 to the first key in the dictionary, and saving the value less than 66 to the value of the second key.

That is: {' K1 ': greater Than, ' K2 ': Less than 66}

View Code

Example two:

View Code

One: Collection series

1: Counter: (Counter)

Counter is a supplement to the dictionary type that is used to track the number of occurrences of a value.

#!/usr/bin/env python

#-*-Coding:utf-8-*-

#导入模块

Import Collections

Collections. Counter

#传一个字符串

#传一个列表

D1 = [11,22,33,111,22,33,11]

D = Collections. Counter (D1)

Print D

#传一个元组

E = (' AA ', ' BBB ', ' AA ', ' B ')

e1 = collections. Counter (e)

Print E1

#迭代器

For item in C.elements ():

Print Item

2: Ordered Dictionary

An ordered dictionary is the same as a dictionary, except that an ordered dictionary is used internally

It is to put all of his keys in a list, the list is ordered, so that the ordered dictionary output is ordered.

The first layer of the ordered dictionary detachment takes effect. But you can keep the internal dictionary going.

3. Default dictionary (defaultdict)

1 obj_file = open (' 1.txt ', ' r+ ')  2  3 Obj_file.seek (3)  4  5 obj_file.truncate ()  6  7 # Do not add all after the pointer is removed  8  

#使用默认字典, define the default type as list,

4, can be named tuple (namedtuple)

Import Collections

#创建一个扩展元组tuple的类 (mainly used in coordinates)

View Code

#原始的元组的创建

View Code

5. Bidirectional Queue (deque)

Both ends can be taken and inserted.

Thread safety.

View Code

6: One-way queue

Queue, FIFO

Stack, mag

Thread-Safe

View Code

Two: Iterators and generators

1: Iterator

For the Python list's for loop, his internal principle: to see if the next element exists, if it exists, then remove it, and if it does not, stopiteration the exception. (Python internal to exception has been handled)

View Code

Example: Application of next function

View Code

2: Generator

Range is not a generator and xrange is a generator

ReadLines is not a generator and xreadlines is a generator

The generator is created internally based on yield, which is created only when used by the generator, thus avoiding memory waste

View Code

3: Bubbling algorithm

Have the following list

[13, 22, 6, 99, 11]

Please follow the rules to calculate:

13 and 22 Compare, put large values on the right side, namely: [13, 22, 6, 99, 11]

22 and 6 Compare, put large values on the right side, namely: [13, 6, 22, 99, 11]

22 and 99 Compare, put large values on the right side, namely: [13, 6, 22, 99, 11]

99 and 42 Compare, put large values on the right side, namely: [13, 6, 22, 11, 99,]

13 and 6 Compare, put large values on the right side, namely: [6, 13, 22, 11, 99,]

3.1 Think

A = 1, b = 2, how can the assignment of A and B convert to each other?

View Code

3.2: Example

View Code

Three: Functions

Category: Built-in functions, custom functions, import (third-party) functions

function declaration, not executed automatically;

Parameters of the function

1 VARs () ===== All variables of the current module  2 print VARs ()  3 print __doc__ #打印当前文件的注释  4 print __name__  5 if __name__ = = ' __main __ ': #确认是不是主函数  6 print ' This is the main function '  7 print __file__ #打印文件的路径  8 All () accepts a sequence, judging that all values are true and return values, otherwise false  9 any ()  As long as there is a true is true, all is false only for false ten li = [' CCC ', ', ', ', ') print all (LI) Lli = ["] Print any (lli) enumerate () Li = [11,22,33,44,55] + for k,v in Enumerate (LI):  print k,v #默认从0开始, specify starting from 1 for k,v in Enumerate (li,1): 2 1  

1: Common built-in functions

The difference between functional programming and process-oriented programming:

Function: A function code is encapsulated in a function, it will not need to be repeated later, only the function can be called

Object-oriented: classify and encapsulate functions to make development "faster, better and stronger ..."

Functional programming The most important thing is to enhance the reusability and readability of code

2: Definition and use of functions

def function name (parameter):

function body

The definition of a function has the following main points

1:def: A keyword that represents a function

2: Function Name: Name of function, call function according to function name later

3: Function Body: A series of logical calculations in a function

4: Parameter: Provide data for function body

5: Return value: When the function is finished, you can return the data to the caller

3: Parameters: (formal parameters and arguments)

General parameters

Common parameters must be passed to the reference

1 # ######### definition function ######### 2 # name is called function func formal parameter, abbreviation: Parameter 3 def func (name): 4  

Default parameters

1: Do not pass; default value is used

2: The default parameter must be placed at the end of the parameter list, or you can have more than one default parameter

1 def func (name, age = 18): 2  

Note: Default parameters need to be placed at the end of the parameter list

Dynamic parameters

1:def func (*args): Can receive tuples and lists

2: Internal Auto-construction tuple

3: If you are passing a sequence, you can use * to avoid the inner tectonic tuple

4:def func (**kwargs): Can receive dictionaries

Dynamic parameter 1:

View Code

Dynamic Parameter 2:

View Code

Dynamic Parameter 3:

View Code

4: Mail Alarm

Example one:

View Code

Example two:

View Code

Four: File operations

1: Basic knowledge

Steps to manipulate files:

Open File-----Action file-----Close File

Open in the way:

Obj_file = open (' path ', ' mode ')

There is also a file way to open, but open is called file mode to execute, it is recommended to use the Open

Open mode:

R: Read-only mode (default)

W: Write-only mode, unreadable, create file if not present, delete contents if present

A: Append mode, readable, nonexistent, create, append, but will be appended to the pointer's position (the position of the pointer below)

R+: Can read and write files, can also be appended (commonly used)

U: Indicates that the \ r \ r \ n (normally used with R, r+) can be automatically converted to \ n when reading.

2: Operating Documentation

View Code

3: Example

File.tell

Show where the pointer is located

View Code

File.seek

Place the pointer where you are executing

View Code

File.truncate

Intercept data

Original file content is: 1234567

Way One:

View Code

Way two:

View Code

Way three:

View Code

Analytical:

One is to start with a file, use truncate, and do not specify size, then delete all after the pointer.

The second way is to delete from the pointer position 3. But the previous 123 in the original file still exists.

The third way is to specify size, only the first three positions, print out the previous 123, and still exist in the original file

4:with

With appears to prevent process consumption by forgetting to close a file after opening it.

How to use:

With open (' db ', R) as Read_file:

With open (' db1 ') as Read_file1,open (' DB2 ') as Read_file2:

Python Foundation case

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.