Friday, October 09, 2009

Python List Operations (map, for comprehensions)

EXAMPLE 1
# Create a list
>>> l = [1,2,3,4,5,6]

# iterate through the list using a for comprehension
>>> [i for i in l]
[1, 2, 3, 4, 5, 6]

# square elements in the list using a for comprehension
>>> [i**2 for i in l]
[1, 4, 9, 16, 25, 36]

# square only even elements in the list using a for comprehension
>>> [i**2 for i in l if i % 2 == 0]
[4, 16, 36]

# iterate through the list using map
>>> map(lambda w: w, l)
[1, 2, 3, 4, 5, 6]

# square each element of the list using map
>>> map(lambda w: w**2, l)
[1, 4, 9, 16, 25, 36]

# or use map to call a separately defined function to# iterate through the list
>>> def squa(x):
...... return x**2

>>> map(squa, l)
[1, 4, 9, 16, 25, 36]

# use map function to call a separately defined function that takes 2 args
>>> l2 = map(lambda w: (w,2),l)
>>> l2
[(1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]

>>> def pow(base, expo):
...... return base**expo

>>> map(lambda (x,y): pow(x,y), l2)
[1, 4, 9, 16, 25, 36]

# filter a list
>>> filter(lambda w: w > 2, l)
[3, 4, 5, 6]

EXAMPLE 2
# define a simple class to play with
>>> class A(object):
...... def __init__(self, x):
........ self.x = x

# create simple list of object instances of the class
>>> l = [A(1), A(2), A(3)]

# use a for (list) comprehension to iterate through the list
>>> [i.x for i in l]
[1, 2, 3]

# use a for comprehension to iterate with a condition
>>> [i.x for i in l if i.x > 1]
[2, 3]

# use map to apply a function to every element in the list
>>> map(lambda w: w.x, l)
[1, 2, 3]

>>> map(lambda w: w.x * w.x, l)
[1, 4, 9]



EXAMPLE 1
# Create a list
>>> l = [1,2,3,4,5,6]

# iterate through the list using a for comprehension
>>> [i for i in l]
[1, 2, 3, 4, 5, 6]

# square elements in the list using a for comprehension
>>> [i**2 for i in l]
[1, 4, 9, 16, 25, 36]

# square only even elements in the list using a for comprehension
>>> [i**2 for i in l if i % 2 == 0]
[4, 16, 36]

# iterate through the list using map
>>> map(lambda w: w, l)
[1, 2, 3, 4, 5, 6]

# square each element of the list using map
>>> map(lambda w: w**2, l)
[1, 4, 9, 16, 25, 36]

# or use map to call a separately defined function to# iterate through the list
>>> def squa(x):
...... return x**2

>>> map(squa, l)
[1, 4, 9, 16, 25, 36]

# use map function to call a separately defined function that takes 2 args
>>> l2 = map(lambda w: (w,2),l)
>>> l2
[(1, 2), (2, 2), (3, 2), (4, 2), (5, 2), (6, 2)]
>>> def pow(base, expo):
...... return base**expo

>>> map(lambda (x,y): pow(x,y), l2)
[1, 4, 9, 16, 25, 36]

# filter a list
>>> filter(lambda w: w > 2, l)
[3, 4, 5, 6]

EXAMPLE 3
# split a list into chunks
>>> map(None, *(iter(range(10)),) * 3)
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
http://stackoverflow.com/questions/1335392/iteration-over-list-slices




No comments: