如何使用`map()`对元组列表进行数学运算? [英] How can I apply a math operation on a list of tuples with `map()`?
本文介绍了如何使用`map()`对元组列表进行数学运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个元组列表
b = [('676010', '5036043'), ('771968', '4754525'), ('772025', '4754525'), ('772072', '4754527'), ('772205', '4754539'), ('772276', '4754542'), ('772323', '4754541'), ('647206', '5036049')]
我正在使用 map()
将其转换为 float
类型。
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]]
如何使用 map()
对元素应用数学运算,比如除以100,000?
How can I apply a math operation on the elements with map()
, let's say divide by 100,000?
我知道以其他方式到达那里,但是如何使用 map()
实现这一目标?
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)]
推荐答案
给映射一个在每个元组上运行的函数:
Give map a function that operates on each tuple:
map(lambda t: (float(t[0]) / 100000, float(t[1]) / 100000), b)
甚至嵌套 map()
函数:
map(lambda t: map(lambda v: float(v) / 10000, t), b)
其中嵌套的 map()
返回列表而不是元组。
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]]
这篇关于如何使用`map()`对元组列表进行数学运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文