User Tools

Site Tools


python:listmap

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python:listmap [2013/03/16 17:40] (current)
Line 1: Line 1:
 +==== How to apply a function on each element of a list ====
 +15.02.2011
 +
 +
 +Suppose that we have a list and we need to apply some function on each element of it. \\ 
 +One good example is getting a file content using readlines(). This function will get every line, **including** the newline (e.g. \n.)
 +
 +
 +One thing we can do is this:
 +
 +<code python>
 +r = []
 +for line in fh.readlines():​
 +    r.append(line.strip())
 +</​code>​
 +
 +But a better way is to use **map** and a **lambda** function:
 +
 +<code python>
 +map((lambda(x):​ x.strip()), self.fh.readlines())
 +</​code>​
  
python/listmap.txt ยท Last modified: 2013/03/16 17:40 (external edit)