12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

for (x, y) in zip(L1, L2):... print x, y, '--', x+y...1 5 -- 62 6 -- 83 7 -- 104 8 -- 12Here, we step over the result of the zip call—that is, the pairs of items pulled fromthe two lists. Notice that this for loop uses tuple assignment again to unpack eachtuple in the zip result. The first time through, it’s as though we ran the assignmentstatement (x, y) = (1, 5).The net effect is that we scan both L1 and L2 in our loop. We could achieve a similareffect with a while loop that handles indexing manually, but it would require moretyping, and would likely be slower than the for/zip approach.The zip function is more general than this example suggests. For instance, it acceptsany type of sequence (really, any iterable object, including files), and more than twoarguments:>>> T1, T2, T3 = (1,2,3), (4,5,6), (7,8,9)>>> T3(7, 8, 9)>>> zip(T1,T2,T3)[(1, 4, 7), (2, 5, 8), (3, 6, 9)]zip truncates result tuples at the length of the shortest sequence when the argumentlengths differ:>>> S1 = 'abc'>>> S2 = 'xyz123'>>>>>> zip(S1, S2)[('a', 'x'), ('b', 'y'), ('c', 'z')]The related (and older) built-in map function pairs items from sequences in a similarfashion, but it pads shorter sequences with None if the argument lengths differ:>>> map(None, S1, S2)[('a', 'x'), ('b', 'y'), ('c', 'z'), (None, '1'), (None, '2'), (None,'3')]This example is actually using a degenerate form of the map built-in. Normally, maptakes a function, and one or more sequence arguments, and collects the results ofcalling the function with parallel items taken from the sequences.When the function argument is None (as here), it simply pairs items, like zip. map andsimilar function-based tools are covered in Chapter 17.Loop Coding Techniques | 269

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!