Can someone kindly explain how the following python code is working? This code is reading a series of integers, which are arranged as 3-tuples.
inverted_list = map(lambda i: (int(numbers[2 + 3*i]),
float(numbers[3 + 3*i]),
float(numbers[4 + 3*i]))
,range(0, (len(numbers) - 2)/3))
Exactly how map and lambda works? Is the lambda really required here?
Thanks.
No, lambda is not really required here, this could also be written as:
I’m not going into the math bit of the indexers, since i’m only on my first cup of coffee today, but what
mapdoes, is apply a function to a sequence, generating a new sequence with the result of the function for each element. Thelambdais the function, in this case creating a tuple from your numbers. The sequence is therangeexpression, that gives you a list ofivalues that you can use in your indexing expressions (e.g.3 + 3*i).The version of your code snippet @gnibbler and I are showing you is modern python. This wasn’t around in, say, python 1.5 – so we used
map,reduce,zipand other “functional” high order operations. I personally like them a lot, but I guess the’re doomed to be replaced for most tasks – the list comprehensions are more expressive in cases like this one!