Welcome to 陈俊峰's ---BeetleHeaded Man Blog !

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  58 随笔 :: 32 文章 :: 18 评论 :: 0 Trackbacks
Note One : Lists Comprehensions
[3*x for x in vec if x > 3]
[x*y for x in vec1 for y in vec2]
......
there expression can used to instead the functional programming tools such as map() ,filter(),reduce()..

Note Two : Some functions in the modules often  be made used of
1.strip()
 :  Return a copy of the string s with leading and trailing whitespace removed.
>>> test_str = '   I Love Python  '
>>> string.strip(test_str)
'I Love Pyhon'    Note that : whitespace at the two side of the string were removed ,but it did not worked on the whitespace between string!
2. str() : can convert the format like int ,long , float ... into string format
>>> num_1 = 3.14
>>> num_2 = 0.618
>>> str(num_1) , str(num_2)
'3.14' '0.618'
3.dict()
dict() -> new empty dictionary.
dict(mapping) -> new dictionary initialized from a mapping object's
    (key, value) pairs.
dict(seq) -> new dictionary initialized as if via:
    d = {}
    for k, v in seq:
        d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs
    in the keyword argument list.  For example:  dict(one=1, two=2)

e.g 
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
dict([(x, x**2) for x in (2, 4, 6)])    
dict(sape=4139, guido=4127, jack=4098)

4. enumerate()
Return an enumerate object.  iterable must be an other object that supports
iteration.  The enumerate object yields pairs containing a count (from
zero) and a value yielded by the iterable argument.  enumerate is useful
for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
Code  show:
>>> for i, v in enumerate(['tic', 'tac', 'toe']):
...     print i, v
...
0 tic
1 tac
2 toe

5 zip()
Return an enumerate object.  iterable must be an other object that supports
iteration.  The enumerate object yields pairs containing a count (from
zero) and a value yielded by the iterable argument.  enumerate is useful
for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...
Code Show:

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print 'What is your %s?  It is %s.' % (q, a)
...	
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

6.sorted()
Code Show:
>>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
>>> for f in sorted(set(basket)):
...     print f
... 	
apple
banana
orange
pear

to be continued......

Note Three : simple statements

7 The yield statement
Download entire grammar as text.

The yield statement is only used when defining a generator function, and is only used in the body of the generator function. Using a yield statement in a function definition is sufficient to cause that definition to create a generator function instead of a normal function.

When a generator function is called, it returns an iterator known as a generator iterator, or more commonly, a generator. The body of the generator function is executed by calling the generator's next() method repeatedly until it raises an exception.

When a yield statement is executed, the state of the generator is frozen and the value of expression_list is returned to next()'s caller. By ``frozen'' we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, and the internal evaluation stack: enough information is saved so that the next time next() is invoked, the function can proceed exactly as if the yield statement were just another external call.

The yield statement is not allowed in the try clause of a try ... finally construct. The difficulty is that there's no guarantee the generator will ever be resumed, hence no guarantee that the finally block will ever get executed.

Note: In Python 2.2, the yield statement is only allowed when the generators feature has been enabled. It will always be enabled in Python 2.3. This __future__ import statement can be used to enable the feature:

from __future__ import generators

8 The raise statement

raise_stmt::="raise" [expression ["," expression ["," expression]]]
Download entire grammar as text.

If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a TypeError exception is raised indicating that this is an error (if running under IDLE, a Queue.Empty exception is raised instead).

Otherwise, raise evaluates the expressions to get three objects, using None as the value of omitted expressions. The first two objects are used to determine the type and value of the exception.

If the first object is an instance, the type of the exception is the class of the instance, the instance itself is the value, and the second object must be None.

If the first object is a class, it becomes the type of the exception. The second object is used to determine the exception value: If it is an instance of the class, the instance becomes the exception value. If the second object is a tuple, it is used as the argument list for the class constructor; if it is None, an empty argument list is used, and any other object is treated as a single argument to the constructor. The instance so created by calling the constructor is used as the exception value.

If a third object is present and not None, it must be a traceback object (see section 3.2), and it is substituted instead of the current location as the place where the exception occurred. If the third object is present and not a traceback object or None, a TypeError exception is raised. The three-expression form of raise is useful to re-raise an exception transparently in an except clause, but raise with no expressions should be preferred if the exception to be re-raised was the most recently active exception in the current scope.

Note Four : Compound Statements

9 The try statement

The try statement specifies exception handlers and/or cleanup code for a group of statements:

try_stmt::=try_exc_stmt | try_fin_stmt
try_exc_stmt::="try" ":" suite
("except" [expression ["," target]] ":" suite)+
["else" ":" suite]
try_fin_stmt::="try" ":" suite "finally" ":" suite
Download entire grammar as text.

There are two forms of try statement: try...except and try...finally. These forms cannot be mixed (but they can be nested in each other).

The try...except form specifies one or more exception handlers (the except clauses). When no exception occurs in the try clause, no exception handler is executed. When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception. An expression-less except clause, if present, must be last; it matches any exception. For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is ``compatible'' with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception, or it is a tuple containing an item that is compatible with the exception. Note that the object identities must match, i.e. it must be the same object, not just an object with the same value.

If no except clause matches the exception, the search for an exception handler continues in the surrounding code and on the invocation stack.

If the evaluation of an expression in the header of an except clause raises an exception, the original search for a handler is canceled and a search starts for the new exception in the surrounding code and on the call stack (it is treated as if the entire try statement raised the exception).

When a matching except clause is found, the exception's parameter is assigned to the target specified in that except clause, if present, and the except clause's suite is executed. All except clauses must have an executable block. When the end of this block is reached, execution continues normally after the entire try statement. (This means that if two nested handlers exist for the same exception, and the exception occurs in the try clause of the inner handler, the outer handler will not handle the exception.)

Before an except clause's suite is executed, details about the exception are assigned to three variables in the sys module: sys.exc_type receives the object identifying the exception; sys.exc_value receives the exception's parameter; sys.exc_traceback receives a traceback object (see section 3.2) identifying the point in the program where the exception occurred. These details are also available through the sys.exc_info() function, which returns a tuple (exc_type, exc_value, exc_traceback). Use of the corresponding variables is deprecated in favor of this function, since their use is unsafe in a threaded program. As of Python 1.5, the variables are restored to their previous values (before the call) when returning from a function that handled an exception.

The optional else clause is executed if and when control flows off the end of the try clause.7.1 Exceptions in the else clause are not handled by the preceding except clauses.

The try...finally form specifies a `cleanup' handler. The try clause is executed. When no exception occurs, the finally clause is executed. When an exception occurs in the try clause, the exception is temporarily saved, the finally clause is executed, and then the saved exception is re-raised. If the finally clause raises another exception or executes a return or break statement, the saved exception is lost. A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation - this restriction may be lifted in the future). The exception information is not available to the program during execution of the finally clause.

When a return, break or continue statement is executed in the try suite of a try...finally statement, the finally clause is also executed `on the way out.' A continue statement is illegal in the finally clause. (The reason is a problem with the current implementation -- this restriction may be lifted in the future).

posted on 2006-04-15 13:13 Jeff-Chen 阅读(384) 评论(0)  编辑 收藏 引用 所属分类: Python

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理