|
Description:
These are just some simple examples of how you can leverage the operator module to help gain performance with something like map (it works great with sort too). There are times where techniques like this may be necessary. Generally, you'd want to avoid doing this simply because it makes python ugly and harder to debug.
Source: Text Source
a= [1,-2,3]
b=[]
for i in a: b.append(abs(i))
print b
print [abs(i) for i in a ]
print map(lambda i:abs(i),a)
>>> [1, 2, 3]
for j in itertools.imap(lambda i:abs(i),a):
print j,
for j in (abs(i) for i in a ):
print j,
>>> 1 2 3
print list(itertools.imap(lambda i:abs(i),a))
>>> [1, 2, 3]
print map(operator.abs,[1,2,3])
>>> [1, 2, 3]
print map(operator.add,[1,2,3],[4,5,6])
>>> [5, 7, 9]
data=( ('fred','jane','ted'),('bill','jane','amy'),('sam','jane','matt'))
print map(operator.contains,data, ('fred','fred','fred'))
>>> [True, False, False]
print map(operator.getslice,data,(0,0,0),(2,2,2))
>>> ('fred', 'jane'), ('bill', 'jane'), ('sam', 'jane')]
print map(operator.getslice,data,(0,)*len(data),(2,)*len(data))
>>> [('fred', 'jane'), ('bill', 'jane'), ('sam', 'jane')]
print map(operator.getitem,data,(1,)*len(data))
>>> ['jane', 'jane', 'jane']
a=['a','b','c','d','e','f']
b=[1,3,5]
print map(operator.getitem,[a]*len(b),b)
>>> ['b', 'd', 'f']
data=( ('fred','jane','ted'),('bill','jane','amy'),('sam','jane','matt'))
print map(operator.itemgetter(1),data)
>>> ['jane', 'jane', 'jane']
data= ( {'name':'fred','score':50},{'name':'betty','score':75})
print map(operator.itemgetter('name'),data)
>>> ['fred', 'betty']
people=(('fred','sam','jane','betty'),(1,2,3,4))
p_dict = {}
map(operator.setitem, [p_dict]*len(people[0]), people[0],people[1])
print p_dict
>>> {'jane': 3, 'betty': 4, 'sam': 2, 'fred': 1}
d1={'a':1,'b':2}
d2={}
old_keys = d1.keys()
new_vals = map(chr, d1.values())
map(operator.setitem, [d2]*len(old_keys), old_keys, new_vals)
print d1
print d2
>>> {'a': 1, 'b': 2}
>>> {'a': '\x01', 'b': '\x02'}
Discussion:
You may gain performance by using a builtin function from the operator module which is implemented in C instead of writing your own that does the same thing. You can also gain performance by using map which loops in C rather than some of other ways of building lists. Thus, if some of the methods from the operator module meet your needs, it is especially fortunate if you can use it with with map. What you lose is readability and perhaps have increased memory usage (itertools can help with that).
Also, the recipe at
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/305304
gives you an example of how you can use operator.itemgetter with sort.
You can reach me at pyguy2 on yahoo.
|