Attack python Article 3: basic, attack python Article 3

Source: Internet
Author: User

Attack python Article 3: basic, attack python Article 3
Basic collection sequence unpacking

Example:

>>>x,y,z=1,2,3>>>print x,y,z1 2 3

It's okay to exchange variables.

>>> X, y = y, x >>> print x, y, z2 1 3 # This is very practical.
This feature is particularly useful when a function or method returns tuples (or other sequences or iteratable objects. If you need to obtain (and delete) any key-value pairs in the dictionary, you can use the popitem method to return the key-value pairs as tuples, then you can directly assign values to the two variables.

Example:

>>> dic1={'name':'lzl','girlfriend':'None'}>>> key,value=dic1.popitem()>>> print key,valuegirlfriend None

When assigning values, the number of elements in the sequence must be the same as the number of variables on the left. Otherwise, an exception valueError occurs.

Note: Python 3.0 another unwrapped feature: asterisks, such as a, B, * test = [1, 2, 3, 4, 5], can be used in the parameter list of functions. in this case, the result of test is [3, 4, 5].

 

Chained assignment

Is a shortcut to assign the same value to multiple variables.

X = y = somefunction () is equivalent to y = somefunction () x = y, but not necessarily the same as the following: x = somefunction () y = somefunction ()
Boolean knowledge supplement

Standard Value False, None, all types of numbers 0, empty sequence, empty dictionary are False; others are True, including special values True

Name =''
While not name or name. isspace ():
Name = raw_input ('Please input your name :')
Print 'hello, % s' % name

 

Practical: When determining whether the input is null or not, if a space is entered, it will be true but imperceptible. You can use the while not name or name. isspace () or while not name. strip ()

 

Assertions

If you need to ensure that a certain condition in the program is true to continue running, the assert statement is useful, which is equivalent to an if statement.

Example:

>>> age = 1>>> assert 0<age <10>>> age = -1>>> assert 0<age<10,'The age must be realistic'Traceback (most recent call last):  File "<input>", line 1, in <module>AssertionError: The age must be realistic
Some iteration tools

In python, iterative sequences (or other iteratable objects) are useful for some functions.

1. Parallel Iteration

names = ['lzl','Bruce Li','damon']age = [18,20,28]print zip(names,ages)

Output: [('lzl', 18), ('Bruce Lil', 20), ('damon ', 28)]

 

Built-inZipFunctions can be used for parallel iteration, as shown in the opposite process of sequence unpacking described above.

The most important thing is that zip can process unequal sequences and stop when the shortest sequence is "used up.

>>> zip(range(5),xrange(100))[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

2. index-based iteration

Sometimes you want to iterate the objects in the sequence and obtain the indexes corresponding to the objects. Built-in functionsEnumerateYou can iterate the index-value pair where the index is provided. The default index starts from 0.

Example:

>>> Li = ['beijing', 'sichuan ', 'chongqing'] >>> for index, string in enumerate (li, 1 ): # index starting from 1... print index, "---", string... 1 --- Beijing 2 --- Sichuan 3 --- Chongqing

Practical: Available for menu options

 

3. Flip and sort Iteration

The reserved and sorted functions are similar to the reserve and sort methods in the same list. However, they act on any and sequences or iteratable objects. Instead of modifying objects in the same place, they return flipped or sorted versions.

Example:

>>> List1 = [4, 3, 6, 2, 1] >>> sorted (list1) [1, 2, 3, 4, 6] >>> list1 # list1 does not change [4, 3, 6, 2, 1] >>> reversed (list1) <listreverseiterator object at 0x02A98C70> list1 # list1 does not change [4, 3, 6, 2, 1]

Note:: Sorted method returns the list, while reserved returns an iteratable object.

 

List derivation-lightweight Loop

List comprehension is a method for creating a new list using other lists (similar to the set derivation in mathematical terms.

>>> [X * x for x in range (10)] [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] >>> [x * x for x in range (10) if x % 3 = 0] # output [0, 9, 36, 81] that can be divisible by 3

Compare to create a list using a for statement:

result = []for a in range(3):    for b in range(3):        result.append((a,b))print result

Output: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2 ), (2, 0), (2, 1), (2, 2)]

Example:

>>> Girls = ['Alice ', 'bernice', 'clarice '] >>> boys = ['chris', 'arnold ', 'bob']> [B + '+ g for B in boys for g in girls if B [0] = g [0] # The first letter must be the same. ['chris + clarice ', 'arnold + alice ', 'Bob + bernice']

 

Built-in functions

While True: if cpu usage> 90%: # send an email reminder to connect to the mailbox server to send an email to close the connection if hard disk space> 90%: # Send email reminder connect to the mailbox server send email close connection if memory usage> 80%: # Send email reminder connect to the mailbox server send email close connection

The above Code indicates that the content under the if condition statement can be extracted and shared as follows:

Def send email (content) # Send email reminder connect to email server to send email close connection while True: if cpu usage> 90%: Send email ('cpu alert ') if disk space> 90%: Send email ('hard disk alert ') if memory usage> 80%:

The second implementation is certainly better than the first reusability and readability for the two methods mentioned above. In fact, this is the difference between functional programming and process-oriented programming:

  • Function: encapsulate a function code into a function. You do not need to write it again later. You only need to call the function.
  • Object-oriented: classifies and encapsulates functions to make development faster, better, and stronger ..."

The most important thing in functional programming is to enhance code reusability and readability.

Functions are defined as follows:

  • · Def: indicates the function keyword.
  • · Function Name: name of the function. The function will be called Based on the function name in the future.
  • · Function body: perform a series of logical calculations in the function, such as sending emails and calculating the maximum number in [11, 22, 38,888, 2... not automatically executed. It is executed only after being called.
  • ·Parameters: Provide data for the function body
  • ·Return Value: After the function is executed, the caller can return data. If no return value is specified, None is returned.
Def function name (parameter):... function body...

Return Value

All functions return things. If no return value is specified, None is returned.

>>> Def test (): print 'this is printed' return # No parameters are received after return. print 'this is not 'to end the function >>> x = test () this is printed

Parameters

Form parameter: variable after the number of letters in the def statement

Note: The parameter is only a variable. assigning a new value to the parameter in the function does not change the value of any external variable, that is, the local scope );

Actual parameters: the real parameters provided when the function is called

Default parameter: It must be placed at the end. Multiple parameters can be entered.

Dynamic parameters:

  

1st types

>>> def func(*args):    print args>>> func(18)(18,)>>> func(18,'qq')(18, 'qq')>>> li=[1,2,'a']>>> func(li)([1, 2, 'a'],)>>> func(*li)(1, 2, 'a')

Features:

  • Multiple parameters are acceptable;
  • Automatically constructs tuples internally, that is, the type of the returned tuples.
  • Add * Before sequence to avoid constructing tuples internally

 

2nd types

>>> Def func (** args ):... print args... >>> func (123) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: func () takes exactly 0 arguments (1 given) >>> func (k1 = 123, k2 = 'abc') # input the parameter {'k2': 'abc' in the form of key = value ', 'k1 ': 123 }>>> dic = {'k1': 18, 'k2': 'lzl' }>>> func (dic) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: func () takes exactly 0 arguments (1 given) >>> func (** dic) # Add ** {'k2': 'lzl', 'k1': 18} to the dictionary type}
  

Features:

1. Only parameters with key = value are accepted.

2. When it is a dictionary, add **

The above verification results show that dynamic parameters are in the form of 'Key = value' in addition to single values. Therefore, if they are used in combination, they are powerful. The forma () method of the same string

>>> help(str.format)Help on method_descriptor:format(...)    S.format(*args, **kwargs) -> string    Return a formatted version of S, using substitutions from args and kwargs.    The substitutions are identified by braces ('{' and '}').

For the above content, refer to "python basic tutorial version 2" and Wu sir blog http://www.cnblogs.com/wupeiqi/articles/4943406.html finishing, the main record points.

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.