12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Why You Will Care: List Comprehensions and mapHere’s a more realistic example of list comprehensions and map in action (we solvedthis problem with list comprehensions in Chapter 13, but we’ll revive it here to addmap-based alternatives). Recall that the file readlines method returns lines with \n endof-linecharacters at the ends:>>> open('myfile').readlines( )['aaa\n', 'bbb\n', 'ccc\n']If you don’t want the end-of-line characters, you can slice them off all the lines in a singlestep with a list comprehension or a map call:>>> [line.rstrip( ) for line in open('myfile').readlines( )]['aaa', 'bbb', 'ccc']>>> [line.rstrip( ) for line in open('myfile')]['aaa', 'bbb', 'ccc']>>> map((lambda line: line.rstrip( )), open('myfile'))['aaa', 'bbb', 'ccc']The last two of these make use of file iterators (which essentially means that you don’tneed a method call to grab all the lines in iteration contexts such as these). The map callis just slightly longer than the list comprehension, but neither has to manage result listconstruction explicitly.A list comprehension can also be used as a sort of column projection operation. <strong>Python</strong>’sstandard SQL database API returns query results as a list of tuples much like the following—thelist is the table, tuples are rows, and items in tuples are column values:listoftuple = [('bob', 35, 'mgr'), ('mel', 40, 'dev')]A for loop could pick up all the values from a selected column manually, but map andlist comprehensions can do it in a single step, and faster:>>> [age for (name, age, job) in listoftuple][35, 40]>>> map((lambda (name, age, job): age), listoftuple)[35, 40]Both of these make use of tuple assignment to unpack row tuples in the list.See other books and resources for more on <strong>Python</strong>’s database API.Because of that, they are often a useful alternative to both computing an entire series ofvalues up front, and manually saving and restoring state in classes. Generator functionsautomatically retain their state when they are suspended—because thisincludes their entire local scope, their local variables keep state information, which isavailable when the functions are resumed.Iterators Revisited: Generators | 361

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

Saved successfully!

Ooh no, something went wrong!