How can I apply a math operation on a list of tuples with `map()`?

拟墨画扇 提交于 2019-12-02 18:34:24

问题


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)]

回答1:


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]]



回答2:


>>> 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)]
>>>


来源:https://stackoverflow.com/questions/21459052/how-can-i-apply-a-math-operation-on-a-list-of-tuples-with-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!