Sorted, Filter and Map


In [43]:
class Person(object):
    def __init__(self,age,name):
        self.age = age
        self.name = name

Lambda


In [44]:
square = lambda x: x**2
print square(10)


100

In [45]:
d = ['potato', 'peach', 'apple', 'grape']
a = [1,2]
print map(lambda x: d[x], a)


['peach', 'apple']

In [46]:
ar = [4]
ar2 = [10]

comp = lambda x,y: x>y
print comp(ar,ar2)


False

Map


In [47]:
ar = [1,2,3,4,5]
map(lambda x:x**x,ar)


Out[47]:
[1, 4, 27, 256, 3125]

Sort


In [48]:
ar = [1,2,3,4,5]
sorted(ar,key=lambda x:(-x))


Out[48]:
[5, 4, 3, 2, 1]

In [49]:
people = [Person(10,'Frank'),Person(50,'Anna'),Person(32,'Louis'),Person(32,'Leonard')]
print "Using List Comprenhension"
print [person.name for person in sorted(people,key=lambda x:(x.age,x.name))]


Using List Comprenhension
['Frank', 'Leonard', 'Louis', 'Anna']

Filter


In [50]:
ar = [1,2,3,4,5]
filter(lambda x:x>4,ar)


Out[50]:
[5]

In [51]:
people = [Person(10,'Paco'),Person(50,'Ana'),Person(32,'Luis'),Person(32,'Anacleto')]
[person.name for person in filter(lambda x:'a'.upper() in x.name.capitalize(), people)]


Out[51]:
['Ana', 'Anacleto']

Combining functions


In [52]:
people = [Person(10,'Frank'),Person(50,'Anna'),Person(32,'Louis'),Person(32,'Leonard')]

print "Older than 43: \t", map(lambda x: (x.age,x.name), filter(lambda x: x.age>43, people))
print "Squaring age: \t", map(lambda x: x.age**2, people)
print "Sorting: \t", map(lambda x: (x.age,x.name), sorted(people, key=lambda x: (x.age,x.name)))


Older than 43: 	[(50, 'Anna')]
Squaring age: 	[100, 2500, 1024, 1024]
Sorting: 	[(10, 'Frank'), (32, 'Leonard'), (32, 'Louis'), (50, 'Anna')]