For ... [If] ... Build list (list comprehension)
1. Simple for ... [If] ... Statement
Python, for ... [If] ... Statement a concise way to build a list, from a for given list, select the element that satisfies the if condition to form a new list, where if is omitted. Here are a few simple examples to illustrate.
>>> a=[12, 3, 4, 6, 7, 21]>>> newlist = [x for x in A]>>> newlist[12, 3, 4, 6, 7, 21]&G t;>> newList2 = [x for x in a If x%2==0]>>> newlist2[12, 4, 6]
After omitting if, NewList constructs a list with the same elements as a. However, NewList and a are different lists. The execution of B=a,b and NewList is different. NewList2 is a list of elements from a that satisfies x%2==0. If you do not use the for ... [If].. Statement, the following action is required to build the NEWLIST2.
>>> newlist2=[]>>> for x in a: ... if x%2 = = 0: ... Newlist2.append (x) >>> newlist2[12, 4, 6]
Obviously, use for ... [If] ... statements are more concise.
2. Nested for ... [If] ... Statement
Nested for ... [If] ... Statement to form a new list of elements that satisfy the IF condition from multiple lists. Here are a few examples.
>>>A=[12, 3, 4, 6, 7, 21]>>>b=[' A ', ' B ', ' X ']>>>newlist=[(x, y) for x in a for y in b]>& gt;>newlist[(b, ' a '), (A, ' B '), (3, ' a '), (3, ' B '), (3, ' X '), (4, ' a '), (4, ' B '), (4, ' X '), (6, ' a '), (6, ' B '), (6, ' X '), (7, ' a '), (7, ' B '), (7, ' X '), (+, ' a '), (+, ' B '), (+, ' x '), (+, ' a '), (+, ' B '), (+, ' x ')]>>> ; newlist2=[(x, y) for x in a for y in B if x%2==0 and y< ' x ']>>>newlist2[(n, ' a '), (4, ' a '), (4, ' B ') '), (6, ' a '), (6, ' B ')]
Nested for ... [If] ... Statement is equivalent to a multiple for statement, the first for statement is the outermost loop.
Use the ELSE clause of Python
In the daily coding, the use of branch statements is very common, often based on whether certain conditions to meet the logic of code execution some control, so everyone to If[elif[else]] must not be unfamiliar. The ELSE clause in the branch statement is executed when other conditions are not satisfied, and the appropriate use of the branch statement can enrich our code logic.
Using the ELSE clause in a branch statement is basically the same usage in some common programming languages, similar to providing a default execution path, using conditional judgment statements with if, and other programming languages (C #, Java, JS, etc.) in Python, else there are some special usages The use of loop statements with for and while, and even with exception handling try except statements, can make our code more concise.
1. Use with For/while Loop statement
After the FOR Loop statement, the ELSE clause is followed, and the logic of the ELSE clause is executed at the end of the loop (in case of an early exit, such as a return or break). Let's look at an example:
def print_prime (n): for I in xrange (2, N): # found = True for J in Xrange (2, i): if I% j = = 0: # Foun D = False break else: print "{} It ' s a prime number". Format (i) # if found: # print "{} It's a prime n Umber ". Format (i)
Print_prime (7)
Results:
2 It s a prime number3 it's a prime number5 it's a prime number
An example of a simple print prime, to determine whether a number is a prime, you need to traverse a small integer than its own, any one satisfies the division of the end of the judgment, otherwise printing this is a prime of info, with the other's plus, the whole example of the logic of the equivalent "Self-expressive", The code is more concise and less descriptive about how to do the "procedural" preparations, as the pseudo-code generally understands and sets the flag value at the end of the function and then determines whether the value of the number is printed at the bottom of the functions.
PS: You can compare the results of the annotated code in the example.
2. Use with try except error control
In an exception-handling statement, else has a similar usage, and the ELSE statement block is executed when the try code block does not throw any exceptions.
def my_to_int (Str_param): try: print int (str_param) except ValueError: print ' cannot convert {} to a Integer '. Format (Str_param) else: print ' convert {} to integer successfully '. Format (Str_param)
My_to_int ("123") My_to_int ("me123")
Results:
123convert 123 to Integer successfullycannot convert me123 to a integer
As shown in the print log, the logic in the ELSE statement will be executed when the conversion succeeds without error, although this example may not have much practical use, but it can roughly illustrate the usefulness of else in fault handling: simplifying logic, Avoid using some of the flag values to be able to accurately grasp whether the error occurred to do some practical operation (such as when the data is saved if an error occurs, in the ELSE statement block rollback operation, and then can be followed by a finally statement to complete some cleanup operations.
The use of the else block allows us to write code that is more concise, closer to the semantics of the natural language, and, of course, more pythonic, and the finer things can be learned slowly.