Question

I have a list of tuples

b = [('676010', '5036043'), ('771968', '4754525'), ('772025', '4754525'), ('772072', '4754527'), ('772205', '4754539'), ('772276', '4754542'), ('772323', '4754541'), ('647206', '5036049')]

I'm using map() to convert them to type float.

In [45]: print [map(float,e) for e in b]
[[676010.0, 5036043.0], [771968.0, 4754525.0], [772025.0, 4754525.0], [772072.0, 4754527.0], [772205.0, 4754539.0], [772276.0, 4754542.0], [772323.0, 4754541.0], [647206.0, 5036049.0]]

How can I apply a math operation on the elements with map(), let's say divide by 100,000?

I know to get there in a different way, but how do I achieve this with map()?

In [46]: print [(float(tup[0])/100000,float(tup[1])/100000) for tup in b]
[(6.7601, 50.36043), (7.71968, 47.54525), (7.72025, 47.54525), (7.72072, 47.54527), (7.72205, 47.54539), (7.72276, 47.54542), (7.72323, 47.54541), (6.47206, 50.36049)]
Was it helpful?

Solution

Give map a function that operates on each tuple:

map(lambda t: (float(t[0]) / 100000, float(t[1]) / 100000), b)

or even nest the map() functions:

map(lambda t: map(lambda v: float(v) / 10000, t), b)

where the nested map() returns a list instead of a tuple.

Personally, I'd still use a list comprehension here:

[[float(v) / 10000 for v in t] for t in b]

Demo:

>>> b = [('676010', '5036043'), ('771968', '4754525'), ('772025', '4754525'), ('772072', '4754527'), ('772205', '4754539'), ('772276', '4754542'), ('772323', '4754541'), ('647206', '5036049')]
>>> map(lambda t: (float(t[0]) / 100000, float(t[1]) / 100000), b)
[(6.7601, 50.36043), (7.71968, 47.54525), (7.72025, 47.54525), (7.72072, 47.54527), (7.72205, 47.54539), (7.72276, 47.54542), (7.72323, 47.54541), (6.47206, 50.36049)]
>>> map(lambda t: map(lambda v: float(v) / 10000, t), b)
[[67.601, 503.6043], [77.1968, 475.4525], [77.2025, 475.4525], [77.2072, 475.4527], [77.2205, 475.4539], [77.2276, 475.4542], [77.2323, 475.4541], [64.7206, 503.6049]]
>>> [[float(v) / 10000 for v in t] for t in b]
[[67.601, 503.6043], [77.1968, 475.4525], [77.2025, 475.4525], [77.2072, 475.4527], [77.2205, 475.4539], [77.2276, 475.4542], [77.2323, 475.4541], [64.7206, 503.6049]]

OTHER TIPS

>>> map(lambda x: tuple([float(x[0])/100000, float(x[1])/100000]), b)
[(6.7601, 50.36043), (7.71968, 47.54525), (7.72025, 47.54525), (7.72072, 47.54527), (7.72205, 47.54539), (7.72276, 47.54542), (7.72323, 47.54541), (6.47206, 50.36049)]
>>>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top