如何舍入嵌套元组列表中的每个浮点数 [英] How to round every float in a nested list of tuples
本文介绍了如何舍入嵌套元组列表中的每个浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的坐标列表:
I have a list of coordinates like this:
[[(-88.99716274669669, 45.13003508233472),
(-88.46889143213836, 45.12912220841379),
(-88.47075415770517, 44.84090409706577),
(-88.75033424251002, 44.84231949526811),
(-88.75283245650954, 44.897062864942406),
(-88.76794136151051, 44.898020801741716),
(-88.77994787408718, 44.93415662283567),
(-88.99624763048942, 44.93474749747682),
(-88.99716274669669, 45.13003508233472)]]
或者像这样:
[[(-88.99716274669669, 45.13003508233472)],
[(-88.46889143213836, 45.12912220841379),
(-88.47075415770517, 44.84090409706577)],
[(-88.75033424251002, 44.84231949526811),
(-88.75283245650954, 44.897062864942406),
(-88.76794136151051, 44.898020801741716)],
[(-88.77994787408718, 44.93415662283567),
(-88.99624763048942, 44.93474749747682),
(-88.99716274669669, 45.13003508233472)]]
或者像这样:
[[(-88.99716274669669, 45.13003508233472, 10),
(-88.46889143213836, 45.12912220841379, 8)]]
嵌套,列表和元组项的数量是可变的.
The number of nestings, lists and tuple items is variable.
当前,我正在这样做:
import json
json.loads(json.dumps(list), parse_float=lambda x:round(float(x), 5))
JSON似乎是不必要的(它已经是列表),但是它简单易读.还有另一种方法可以解决这个问题吗?
The JSON seems unnecessary (it's already a list), but it's simple and readable. Is there another way to solve this?
推荐答案
我不知道最快速"(最快速写?读?运行时?),但这是我递归编写的方式:>
I don't know about "quickest" (quickest to write? read? runtime?), but this is how I'd write it recursively:
def re_round(li, _prec=5):
try:
return round(li, _prec)
except TypeError:
return type(li)(re_round(x, _prec) for x in li)
演示:
x = [[(-88.99716274669669, 45.13003508233472), (-88.46889143213836, 45.12912220841379), (-88.47075415770517, 44.84090409706577), (-88.75033424251002, 44.84231949526811), (-88.75283245650954, 44.897062864942406), (-88.76794136151051, 44.898020801741716), (-88.77994787408718, 44.93415662283567), (-88.99624763048942, 44.93474749747682), (-88.99716274669669, 45.13003508233472)]]
re_round(x)
Out[6]:
[[(-88.99716, 45.13004),
(-88.46889, 45.12912),
(-88.47075, 44.8409),
(-88.75033, 44.84232),
(-88.75283, 44.89706),
(-88.76794, 44.89802),
(-88.77995, 44.93416),
(-88.99625, 44.93475),
(-88.99716, 45.13004)]]
(该函数的旧生成器版本,用于后代:)
(old generator version of the function, for posterity:)
def re_round(li, _prec=5):
for x in li:
try:
yield round(x, _prec)
except TypeError:
yield type(x)(re_round(x, _prec))
这篇关于如何舍入嵌套元组列表中的每个浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文