about lambda

S

Shi Mu

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)

Thanks!
 
B

bonono

Shi said:
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,[])
 
D

Duncan Booth

Shi said:
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)

Thanks!

Assuming b is a dict, it is roughly equivalent to the following (except
that the variables beginning with _ don't exist):

_result = []
for _key in a:
if _key not in b:
b[_key] = []
_result.append(b[_key])

A more usual way to write this would be:

result = [b.setdefault(key, []) for key in a]

I added an assignment because I'm assuming that even though you didn't show
it the original expression made some use of the resulting list, otherwise
it is just wasting time and effort obfuscating something which could be
more simply written as:

for key in a:
if key not in b:
b[key] = []
 
R

Rick Wotnaz

Shi said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top