about lambda

Rick Wotnaz desparn at wtf.com
Sun Nov 20 16:44:36 CET 2005

"bonono at gmail.com" <bonono at gmail.com> wrote in 
news:1132494099.642274.220720 at g14g2000cwa.googlegroups.com:

> Shi Mu wrote:
>> what does the following code mean? It is said to be used in the
>> calculation of the overlaid area size between two polygons.
>> map(lambda x:b.setdefault(x,[]),a)
> The equivalent of :
> def oh_my_yet_another_function_name_why_not_use_lambda(x):
>   b.setdefault(x,[])
> map(oh_my_yet_another_function_name_why_not_use_lambda, a)
> Or
> for x in a:
>   b.setdefault(x,[])

Or even:
[b.setdefault(x,[]) for x in a]

The effect of the code is this: if you have b, a dictionary of 
values, and a, a list or tuple of indexes to the dictionary, you 
can generate a list that will contain just the values associated 
with the indices in the list. If the index is not found in the 
dictionary, the default value will be used; in this case, that is 
an empty list.

So, for example, if you have 
b = {'x':1,1:(1,2,3),'arthur':'A string',99:{'j':45,'k':111}}
and a looks like this:         you produce this:
a = (0,1,'x')                  [[], (1, 2, 3), 1]
a = (0,2,3,22)                 [[], [], [], []]
a = ['x','arthur']             [1, 'A string']

... and so on.

More information about the Python-list mailing list