Conditions and cycle python - cycle

1 while statement

while for implementing the loop, by judging whether a condition is true, to decide whether to continue.

 1.1 The general syntax

 The syntax is as follows:

while expression:

  suite_to_repeat

Count 1.2

 1  2 
 3 >>> cnt = 0
 4 
 5 >>> while(cnt < 9):
 6 
 7 ... print 'the index is ', cnt
 8 
 9 ... cnt += 1
10 
11 ...
12 
13 the index is 0
14 
15 the index is 1
16 
17 the index is 2
18 
19 the index is 3
20 
21 the index is 4
22 
23 the index is 5
24 
25 the index is 6
26 
27 the index is 7
28 
29 the index is 8

The print and block contains increment statements, will be repeatedly executed, no less than 9 cnt know.

 1.3 infinite loop

 while True:

  suite_to_repeat

Conditional expression has been true.

 2 for statement

 statement is for another cycle python provides the mechanism to be used to traverse the sequence listing may be used in the analysis and generation of the expressions.

 2.1 The general syntax

 All elements of a for loop iteration access object (such as a sequence or Adder) is, after the end of the cycle and processing all entries. The syntax is as follows:

for iter_var in iterable:

  suite_to_repeat

Each loop, iter_var iteration variable is set to be the current element in the iteration objects (sequence, iteration iterator objects or other support), there is provided the use of a block of statements suite_to_repeat.

 2.2 for sequence type

 Introduces a different sequence for loop iterates objects: strings, lists and tuples.

Iterative sequence of three ways:

(1) by an iterative sequence of item

Each iteration, eachName variables are set to a specific list element.

(2) by an iterative sequence index

>>> namelist = ['Bob', 'Lisa', 'Henry']

>>> for nameIndex in range(len(namelist)):

... print namelist[nameIndex]

...

Bob

Lisa

Henry

Use len () function to get the length of the sequence, using the range () function to create a sequence of iterations.

(3) the use of terms and index iteration

Use the built-in the enumerate () function

>>> namelist = ['Bob', 'Lisa', 'Henry']

>>> for i, eachName in enumerate(namelist):

... print i,eachName

...

0 Bob

1 Lisa

2 Henry 

3 range () built-in function 

range () complete syntax is as follows:

range([start,] stop[, step])

range () returns a list of all of k (start <= k <end), from start to end, k is incremented each time step, step 0 is not.

>>> range(3, 7)

[3, 4, 5, 6] 

4 built-in functions related to the sequence 

sorted()、reversed()、enumerate()、zip()

reversed (): returns an iterator access reverse order;

 1 >>> namelist = ['Bob', 'Lisa', 'Henry']
 2 
 3 >>> years = [1978, 1989, 1990, 2003]
 4 
 5 >>> for name in sorted(namelist):
 6 
 7 ... print name,
 8 
 9 ...
10 
11 Bob Henry Lisa
12 
13 >>> namelist
14 
15 ['Bob', ''Add, 'Henry']
16 
17 >>> for name in reversed(namelist):
18 
19 ... print name,
20 
21 ...
22 
23 Henry Lisa Bob
24 
25 >>> for i, name in enumerate(namelist):
26 
27 ... print i, name
28 
29 ...
30 
31 0 Bob
32 
33 1 Lisa
34 
35 2 Henry
36 
37 >>> for name, year in zip(namelist, years):
38 
39 ... print year, name
40 
41 ...
42 
43 1978 Bob
44 
45 1989 Lisa
46 
47 1990 Henry

5 break statement 

break statement is used to end the current cycle jump to the next statement. 

6 continue Statement 

When the continue statement is encountered, the program terminates the current cycle, and ignore the rest of the statements, and then return to the top of the cycle. In the beginning of the previous iteration, if it is conditional loop (while loop), the verification conditional expression; if the case is iterative loop (for loop), you can verify whether there are elements of iterations, only the validation is successful, it came under iteration.

>>> valid = False
>>> count = 3
>>> while count > 0:
...     input = raw_input('Enter passsword:')
...     for eachPasswd in passwdList:
...         if input == eachPasswd:
...             valid = True
...             break
...         if not valid:
...             print "invalid input"
...             count -= 1
...             continue
...         else:
...             break

7 pass sentence 

The pass statement does not do anything (ie, NOP, No Operation, no operation) for not writing any statement in place that require a statement block.

8 and iterator ITER () function

Basically, there is an iterator object next () method, rather than counting index. When you or a circulation mechanism needs next, call the iterator next () method can get it.

Iterator class provides a serial interface objects like sequences, which are a set of data structures, they can be used has an index from 0 "iteration" of the sequence to the last entry.

8.1 iterators

(1) Sequence

>>> i = iter(myTuple)

>>> i.next()

123

>>> i.next()

'abc'

>>> i.next()

45.600000000000001

>>> i.next()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

StopIteration

Automatically generating a sequence of bytes thereof iterators.

for I in seq:

do_something_to(i)

(2) Dictionary

python dictionary data types are also iterative. Dictionary iterator will traverse its key (key). Statement for eachKey in myDict.keys () can be abbreviated for eachKey in myDict.

>>> myDict = {'a':10, 'b':20, 'c':30}

>>> for eachKey in myDict:

... print eachKey, myDict[eachKey]

...

a 10

c 30

b 20

Further, python as well as three new built-in dictionary to define an iterative method: myDict.iterkeys () (key by iterations), myDict.itervalues ​​() (by value iteration) and myDict.iteritems () (through the key - the value of the iteration ).

(3) file

File object iterator generated automatically calls readline () method, the cycle can access all lines of text files, you can use for eachline in myFile replacement for eachline in myFile.readlines ()

>>> myFile = open('testfile.txt')

>>> for eachline a myFile:

... print eachline

...

8.2 Creating iterator

Calls iter to an object () you can get it iterators. The syntax is as follows:

path (obj)

travel (func, sentinel)

If you pass a parameter to the iter (), parameter checks passed is not a sequence, if it is, the end of the sequence index from 0 up to iteration based on. If the two parameters are passed to iter (), the call will be repeated func, until the next iteration is equal to the value of sentinel.

9 list comprehension

List comprehension can be used to dynamically create a list, the syntax is as follows:

[expr for iter_var in iterable]

Expr applied to each member of the foregoing sequence, the final result is the list of expression values ​​generated. Iteration variable does not need to be part of the expression.

>>> [x**2 for x in range(6)]

[0, 1, 4, 9, 16, 25]

It can also be used in conjunction with expression and if extended syntax is as follows:

[expr for iter_var in iterable if cond_expr]

This syntax will filter or "capture" to meet members of the sequence of conditional expression cond_expr.

>>> [x for x in range(6) if x % 2]

[1, 3, 5]

(1) Example: Sample Matrix

3 as a matrix of rows and five columns

>>> [(x+1, y+1) for x in range(3) for y in range(5)]

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]

10 generator expression

Generator expressions are an extension of the list comprehension. Builder is a special function that allows you to return a value, then do a "pause" code is later restored.

Lack of resolve is necessary to generate a list of all the data used to create the entire list. Similar to the basic syntax and list builder, but not really to create a list of numbers, but returns a generator, the generator is calculated each time an entry, this entry "produce" (yield) out.

Generator expression as follows:

(expr for iter_var in iterable if cond_expr)

(1) For example: the cross pair Sample

>>> rows = [1, 2, 3, 17]
>>> def cols():
...     yield 56
...     yield 2
...     yield 1
>>> x_product_pairs = ((i, j) for i in rows for j in cols())
>>> for pair in x_product_pairs: ... print pair ... (1, 56) (1, 2) (1, 1) (2, 56) (2, 2) (2, 1) (3, 56) (3, 2) (3, 1) (17, 56) (17, 2) (17, 1)

(2) the reconstructed samples

Obtain maximum file length of line:

1 f = open('/etc/motd','r')
2 
3 longest = max(len(x.strip()) for x in f)
4 
5 f.close()
6 
7 return longest

Simplified as follows:

1 return max(len(x.strip()) for x in open('/etc/motd')) 

Guess you like

Origin www.cnblogs.com/mrlayfolk/p/12000495.html