第十三章 while and for Loops

来源:互联网 发布:不调用淘宝客api 编辑:程序博客网 时间:2024/06/03 22:01

1.while Loops

General Format:

while test: # Loop test    statements # Loop bodyelse: # Optional else    statements # Run if didn't exit loop with break

break, continue, pass, and the Loop else

  • break:Jumps out of the closest enclosing loop (past the entire loop statement)
  • continue:Jumps to the top of the closest enclosing loop (to the loop’s header line)
  • pass:Does nothing at all: it’s an empty statement placeholder
  • Loop else block:Runs if and only if the loop is exited normally (i.e., without hitting a break)

General Loop Format:

while test:    statements    if test: break # Exit loop now, skip else if present    if test: continue # Go to top of loop now, to test1else:    statements    # Run if we didn't hit a 'break'

2.for Loops

General Format:

for target in object: # Assign object items to target    statements # Repeated loop body: use target    if test: break # Exit loop now, skip else    if test: continue # Go to top of loop nowelse: # Optional else part    statements # If we didn't hit a 'break'
循环结束时x仍然保留最后一个元素


Tuple assignment in for loops:

>>> T = [(1, 2), (3, 4), (5, 6)]>>> for (a, b) in T: # Tuple assignment at work... print(a, b)...1 23 45 6

Python 3.X extended sequence assignment in for loops

>>> for (a, *b, c) in [(1, 2, 3, 4), (5, 6, 7, 8)]:... print(a, b, c)...1 [2, 3] 45 [6, 7] 8

>>> seq1 = "spam">>> seq2 = "scam">>> [x for x in seq1 if x in seq2] # Let Python collect results['s', 'a', 'm']

3.Loop Coding Techniques

  • The built-in range function (available since Python 0.X) produces a series of successively higher integers, which can be used as indexes in a for.
  • The built-in zip function (available since Python 2.0) returns a series of parallelitem tuples, which can be used to traverse multiple sequences in a for.
  • The built-in enumerate function (available since Python 2.3) generates both the values and indexes of items in an iterable, so we don’t need to count manually.
  • The built-in map function (available since Python 1.0) can have a similar effect to zip in Python 2.X, though this role is removed in 3.X


Python 2.X range creates a physical list; in 3.X, range is an iterable that generates items on demand:

>>> list(range(5)), list(range(2, 5)), list(range(0, 10, 2))([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8])


Parallel Traversals: zip and map

zip is a list in Python 2.X, but an iterable object in 3.X

>>> L1 = [1,2,3,4]>>> L2 = [5,6,7,8]>>> list(zip(L1, L2)) # list() required in 3.X, not 2.X[(1, 5), (2, 6), (3, 7), (4, 8)]>>> T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)>>> T3(7, 8, 9)>>> list(zip(T1, T2, T3)) # Three tuples for three arguments[(1, 4, 7), (2, 5, 8), (3, 6, 9)]

zip truncates result tuples at the length of the shortest sequence

>>> S1 = 'abc'>>> S2 = 'xyz123'>>>>>> list(zip(S1, S2)) # Truncates at len(shortest)[('a', 'x'), ('b', 'y'), ('c', 'z')]

Generating Both Offsets and Items: enumerate

>>> S = 'spam'>>> for (offset, item) in enumerate(S):... print(item, 'appears at offset', offset)...s appears at offset 0p appears at offset 1a appears at offset 2m appears at offset 3

>>> E = enumerate(S)>>> E<enumerate object at 0x0000000002A8B900>>>> next(E)(0, 's')>>> next(E)(1, 'p')>>> next(E)(2, 'a')>>> [c * i for (i, c) in enumerate(S)]['', 'p', 'aa', 'mmm'

0 0