Transforming a list of data in Python: Difference between revisions

From XPUB & Lens-Based wiki
(Created page with "Exercise to be typed in ipython. <source lang="python"> range(100) data = range(100) for d in data: print d for d in data: print d*17 pp = [] for d in data: pp.a...")
 
No edit summary
 
(2 intermediate revisions by one other user not shown)
Line 1: Line 1:
Exercise to be typed in ipython.
Exercise to be typed in ipython.
To test, you can use the ''range'' function to get some "sample" data to work with:


<source lang="python">
<source lang="python">
range(100)
data = range(100)
data = range(100)


for d in data:
for d in data:
     print d
     print d
</source>
Imagine you want to multiply each number by 17.


<source lang="python">
for d in data:
for d in data:
     print d*17
     print d*17
</source>
== Iterate & Append to a new list ==
A general purpose technique to translate the items of one list to another is to:<br>
1. Create a new empty list<br>
2. Iterate over the original list<br>
3. Use the list.append function to add (transformed) items onto the new list


<source lang="python">
pp = []
pp = []
for d in data:
for d in data:
Line 22: Line 35:
pp
pp
</source>
</source>
== List comprehensions ==
Python also supports a more mathematically inspired notation called List Comprehensions. The result is more compact, and may or may not be easier to read.
<source lang="python">
p = range(100)
pp = [x*17 for x in p]
</source>
[[Category: Cookbook]][[Category: Python]][[Category: Lists]]

Latest revision as of 15:43, 5 April 2011

Exercise to be typed in ipython.

To test, you can use the range function to get some "sample" data to work with:

data = range(100)

for d in data:
    print d

Imagine you want to multiply each number by 17.

for d in data:
    print d*17

Iterate & Append to a new list

A general purpose technique to translate the items of one list to another is to:
1. Create a new empty list
2. Iterate over the original list
3. Use the list.append function to add (transformed) items onto the new list

pp = []
for d in data:
    pp.append(d)
pp

pp = []
for d in data:
    pp.append(d*17)
pp

List comprehensions

Python also supports a more mathematically inspired notation called List Comprehensions. The result is more compact, and may or may not be easier to read.

p = range(100)
pp = [x*17 for x in p]