In [55]:
x = [1,2,3]
lambda x: max(x)
Out[55]:
In [56]:
a = range(-5,5)
## with builtins
b = map(abs,a)
c = [abs(x) for x in a]
print b==c,b
## with your own function
b = [x**2 for x in a]
print b==c,b
In [57]:
import types
## filter
a = ['', 'fee', '', '', '', 'fi', '', '', '', '', 'foo', '', '', '', '', '', 'fum']
b = filter(lambda x: len(x) > 0,a)
c = [x for x in a if len(x) > 0]
print b==c,b
## square only the ints and filter the rest
a = [1, '4', 9, 'a', 0, 4]
b = [ x**2 for x in a if type(x)==types.IntType ]
c = map(lambda x: x**2, filter(lambda x: isinstance(x,int) == True,a))
print b==c,b
In [ ]:
a = [1, 2, 3, 4]
[elem*2 for elem in
[item+1 for item in li] ]
In [58]:
a1,a2 = [1,2,3],['a','b','c']
print zip(a1,a2)
print zip(*[a1,a2])
In [59]:
dict(zip(a2,a1))
Out[59]:
In [60]:
## transpose
a = [[1,2,3],[4,5,6]]
print(a)
b = map(list, zip(*a))
c = [[row[i] for row in a] for i in range(len(a[0]))]
print b==c,b
## rotate (to the right 90 degrees)
b = map(list, zip(*a[::-1]))
c = [[row[i] for row in a[::-1]] for i in range(len(a[0]))]
print b==c,b
In [63]:
## Are list comprehensions always easier?
b = map(lambda x: max(x), zip(*a))
## what is the equivalent list comprehension?
c =[max(tpl) for tpl in [[row[i] for row in a] for i in range(len(a[0]))]]
print b==c,b
In [ ]: