Python learns _05_ conditions, loops

Source: Internet
Author: User
Tags iterable

Conditions

Similar to other languages, Python uses if...elif...else to form branches, supporting three-mesh operators? : There is no switch in Python, but the indentation feature makes the IF...ELIF...ELSE structure as easy to read

Loop control

In Python, in addition to the Break,continue two general loop control statements, there is a pass that performs an empty operation. Due to the syntax of Python, adding a pass can leave a domain blank, avoiding repeated errors during debugging.

While loop

The while loop in Python adds an attribute to other languages: support else. In other languages, it is often used to determine whether a normal end loop or a halfway break is over, and Python uses while...else to solve this problem succinctly and concisely:

i = 0
s = ' This is a test string '
While I < Len (s):
? ? If s[i] = = ' Z ':
? ? ? ? Break
? ? i + = 1
Else
? ? Print "There is no z in the string"

Because break jumps out of the entire while, including else, the statement after else can be executed at the normal end of the case.

For loop

The For loop in Python is more like a foreach in Perl, supports features such as iterators, and is very powerful

For accesses each element in an iterative object and ends the loop after all the elements have been accessed, iterating over the objects including sequences, dictionaries, collections, iterators, and so on.

1. Direct Loop Sequence Entry: This is the most straightforward way to cycle:

Alist = [' A ', ' B ', ' C ', ' D ']
foreach value in alist:
? ? Print "value=", value

If it is a dictionary type, direct access returns the key, not the value

2. Access the sequence through the sequence index: by using the range () function, the index sequence of the sequence is established, and then by iterating through the index sequence to access the original sequence, in some cases it is necessary to extract the index value:

Alist = [' A ', ' B ', ' C ', ' D ']
foreach index in range (len (alist)):
? ? Print "index=%i,value=%s"% (Index,list[index])

The full syntax of the range () method is range (start,end,step=1), Range (1,10,2) creates an odd sequence of 1 to 9, omits the last argument, the step defaults to 1, and when the two arguments are omitted, the range () syntax is range (end), The default is 0, and the step size is 1 and is immutable:

Print Range (1,10,2)
Print Range (1,10)
Print Range (10)

3. Access both the index and the content: through the enumerate () function, build a enumerate object, for Each loop you can get the corresponding tuple of index and content from that object, and if it is a dictionary, use enumerate () The Iteritems method only extracts the key and its corresponding index (note the disorder of the Dictionary key) and wants to access the dictionary key and value at the same time, you need to pass the dictionary's () method:

Adict = {' A ': ' B ', ' C ': ' D ', ' EEE ': ' F '}
For k,v in Adict.iteritems ():
? ? Print K,v
Alist = [' A ', ' B ', ' C ', ' D ']
For k,v in Enumerate (alist):
? ? Print K,v

iterators

Iterators and sequences are different, not counted by index, iterators are objects with a next () method, the For statement uses the next () method to get the next item, and after the entry is all fetched, a Stopiteration exception is thrown to complete the iteration.

The ITER method allows you to generate an iterator that, in fact, will be iterated over as an iterator during the for loop. The dictionary iterator only iterates through the keys of the dictionary, so when using the for key in Adict, the loop is the key, and the dictionary can use dict.iter* to generate an iterator to the key, value, and key-value pairs.

Iterators are immutable, so it is not possible to change the corresponding object during iterating through the iterator, and if a change is required, you need to return a list of keys using the keys () method, and then change the object by iterating through the index or key.

List Builder

In the use of the For loop, you can see that the range () method enables you to implement the simple functionality of for in other languages, and you can complete the functionality of for in other languages by generating a unique list from the List Builder.

List resolution:

[Expr for Iter_var in iterable if COND_EXPR]

Generator expression:

(Expr for Iter_var in iterable if cond_expr)

The generator can get a more memory-friendly result, he does not create a list of numbers, but after each calculation of an entry, it is said that the entry is generated, the way the generator delays the calculation to make it more efficient in memory.

With the generator, you can simplify the code very much, and optimize the memory structure.

A 3*3 matrix can be formed by [(x, Y) for x in range (3) for Y in range (3)], while the generator does not generate matrices in memory, but instead computes and produces results. To count the number of non-empty bytes in a file, using list resolution directly may consume a large amount of memory, such as using the sum (len) for lines in the data for Word in line.split () generator, you can access the file row by line without consuming memory beforehand.

With generators, you can refactor some of the more complex code, such as the length of the longest line in a file:

f = open (' file ', ' R ')
Alllinelens = [Len (X.strip ()) for x in F]?
F.close ()
Return Max (Alllinelens)

A list is parsed in Alllinelens that reads the entire file into memory, using the generator:

Return Max (Len (X.strip ())) for X in open (' file ')

It can be read row by line, optimizing memory while simplifying code.

Python is widely used in scientific computing, scientists are hate loops of thinking, the way the generator is the structure of the data more visually displayed, more in line with the thinking habits of scientists should also have a great relationship.

Python learns _05_ conditions, loops

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.