Python study notes - the basics summary 03

1. Common functions:

    abs (): absolute value;

    cmp (valA, valB): two comparison values;

    int (val): converting the other data types are integers;

    str (val): is converted to the other data types str;

    sum ([1,2,3]): and receiving a return to the List List sum;

    range (1, 101): creating a series of from 1 to 100;

    zip () function can be two list into a list:

    isinstance (x, str) can be determined whether the variable x is a string;

    upper();

    len (args)

2. function definition:

    def function name (parameter list):

    Ps. If the function does not return statement, the function will return the results of execution after completion, but the result is None.

3. The return value:

   Return value of the function is typically a value, but may be a plurality of return values ​​returned Turple form;

4. recursive function:

    A function calls itself within itself, this function is a recursive function.

The default parameters:

    The following code, name = 'world' is the default parameters;

    def greet(name='world'):

  print 'Hello,',name,'.'

 greet ()
   greet (Bart)

6. The variable parameters

   If you want a function can accept any number of parameters, we can define a variable parameter:

def fn(*args):
    print args

  In front of the name of the variable parameters have a asterisk, we can pass in 0, one or more parameters to the variable parameters:

7. slice (taken part)

    7.1 pairs of slice list (list of some elements taken): slice ()

          >>> L[0:3]

   ['Adam', 'Lisa', 'Bart']

         A. L [0: 3] represents a start index taken from 0, until the index 3 (excluding 3)

         . b If the first index is 0, may also be abbreviated as: L [: 3]

         . c  may start from the index 1, two elements taken out: L [1: 3]

         d.  only a: represents Remove all elements: L [:]

         . E  slicing operation may also specify the third parameter, taken every N a L [:: 2] taken from the beginning to the end of said each take a two.;

    7.2 pairs tuple sliced

          As with slices of list, which I will not explain!

    7.3 descending sections: L [-1:]

    7.4 pairs of string sections: 'ABCDEFG' [: 3] => 'ABC'

          Python is not taken for the function string, only a slice operation can be completed.

8. Iteration

     In Python 8.1, if given a list or tuple, we can traverse the list or tuple through the for loop, we traverse this become iteration.    

     Ordered collection: list, tuple, str and unicode;

     Unordered set: set 

     And unordered set of key-value pairs having: dict

    8.2 iteration index

          Python, iteration is always the element itself out, rather than the index of the element. For an ordered collection of elements is indeed indexed. Sometimes, we do want to get the index for the cycle, is to use enumerate () function:          

          for index, name in enumerate(L):

                 print index, '-', name

Use enumerate () function, we can simultaneously bind index index and element name in a for loop. However, this is not enumerate () special syntax. Indeed, enumerate () function to: [ 'Adam', 'Lisa', 'Bart', 'Paul'] becomes similar to: [(0, 'Adam'), (1, 'Lisa'), (2 , 'Bart'), (3, 'Paul')] Thus, each iteration of the element is actually a tuple:

    for t in enumerate(L):
        index = t[0]
        name = t[1]
        print index, '-', name

If we know each tuple element contains two elements, for loop can be further abbreviated to:

    for index, name in enumerate(L):
        print index, '-', name

This will not only code simpler, but also less two assignments. Visible, not really iteration index by index access, but by enumerate () function automatically becomes every element (index, element) such a tuple, then the iteration, it also won the index and the element itself.

     8.3 iteration dict of value

           We have learned a dict object itself is iterables, with a for loop iteration dict directly, you can get a time of a key dict. If we want iteration dict objects of value, how should we do? dict object has a values ​​() method, which converts dict into a list that contains all the value, so we each iteration is a value of dict.

           dict object has a values ​​() method, which converts into a dict contains a list of all value. In addition to the values ​​() method, there is a itervalues ​​() method. itervalues ​​() method does not convert, it iterative process dict sequentially removed from the value, so itervalues ​​() method ratio values ​​() method saves memory required to generate the list.

           In Python, a for loop iteration object can act much more than list, tuple, str, unicode, dict, etc., any object can act on iterative for loop, while the internal iteration how we usually do not use care. If an object can say that they iteration, then we go directly for loop iterations it can be seen, iteration is an abstract data manipulation, it does not iterative data inside the object have any requests.

    Dict 8.4 iteration of key and value

          First, items () method to convert the object became dict contains list tuple, we iterate on this list, you can obtain a key and value at the same time. And values ​​() has a itervalues ​​() Similarly, items () has a iteritems (), iteritems () corresponding to not convert into a dict List, but constantly given tuple in an iterative process, therefore, iteritems () does not take additional memory.

9. List formula

     9.1. To generate a list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], we can use the range (1, 11). But if you want to generate [1x1, 2x2, 3x3, ..., 10x10] how to do? The first loop method:

>>> L = []
>>> for x in range(1, 11):
...    L.append(x * x)
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

However, the cycle too complicated, and the list of the formula may be replaced with a line loop statement results in the above List, such an approach is that the list of specific formula Python.

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

        9.2. Complex Expressions

                Use a for loop iteration iteration not only an ordinary list, you can also iterative dict. Suppose the following dict:

          d = { 'Adam': 95, 'Lisa': 85, 'Bart': 59 }

                 Can generate a list through a complex formula to turn it into an HTML table:

tds = ['<tr><td>%s</td><td>%s</td></tr>' % (name, score) for name, score in d.iteritems()]
print '<table>'
print '<tr><th>Name</th><th>Score</th><tr>'
print '\n'.join(tds)
print '</table>'

                 Note: string can be formatted by%,% s alternate with the specified parameters. join string () method can be put together into a string list. Save print out the results as a html file, you can see the effect in the browser.

        9.3 Conditions filter

               The formula for the list can also add back loop if the judge. For example: >>> [x * x for x in range (1, 11)]

          [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

        9.4 Multilayer expression

               for loops can be nested, therefore, in the list in the formula, it can also be used for multilayer loop generating a list. For the string 'ABC' and '123', two loop may be used to generate a full array: >>> [m + n for m in 'ABC' for n in '123']

[ 'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3']

               Translated into the loop code like this:

L = []
for m in 'ABC':
    for n in '123':
        L.append(m + n)

Guess you like

Origin www.cnblogs.com/sccd/p/10147320.html