在一串点上拆分和映射浮点函数的有效方法

Efficient way to split and map float function on a string of points

如何使用map/any其他高级函数生成点数组? 我正在使用下面的代码,它运行良好,但不可读或者它是非常基本的版本。

有什么方法可以使用一些高级技巧来生成相同的输出吗?我正在阅读 map() 函数,我们可以使用类似 list(map(int, [3.3,4.3,5.3])).

的函数
t = "517.30,363.60;511.27,385.41;508.63,406.12;505.62,424.20;502.23,444.91;500.35,468.26"
# line below, but is not readable, not sure about performance
points = [[float(x.split(',')[0]),float(x.split(',')[1])] for x in t.split(';')]
print(points)

输出:

[[517.3, 363.6], [511.27, 385.41], [508.63, 406.12], [505.62, 424.2], [502.23, 444.91], [500.35, 468.26]]

您在 Python 中实际需要 map 的情况很少见。一般来说,你最好使用 list/dict 理解:

points = [[float(i) for i in x.split(',')]
          for x in t.split(';')]

使用 map 缩短它并将其分成两行以便于阅读:

>>> [[*map(float, x.split(','))]
     for x in t.split(';')]
[[517.3, 363.6], [511.27, 385.41], [508.63, 406.12], [505.62, 424.2], [502.23, 444.91], [500.35, 468.26]]

或者如果元组没问题(看起来它们可能是):

>>> [*map(ast.literal_eval, t.split(';'))]
[(517.3, 363.6), (511.27, 385.41), (508.63, 406.12), (505.62, 424.2), (502.23, 444.91), (500.35, 468.26)]

将我的第一个与 Eugene 的进行比较(三轮,结果相当稳定,时间如此之低=更快):

0.905 Eugene Pakhomov
0.869 superb rain

0.905 Eugene Pakhomov
0.864 superb rain

0.909 Eugene Pakhomov
0.867 superb rain

代码:

from timeit import repeat

funcs = {
    'Eugene Pakhomov': lambda: [[float(i) for i in x.split(',')]
                                for x in t.split(';')],
    'superb rain':     lambda: [[*map(float, x.split(','))]
                                for x in t.split(';')],
}

t = "517.30,363.60;511.27,385.41;508.63,406.12;505.62,424.20;502.23,444.91;500.35,468.26"

for _ in range(3):
    for author, func in funcs.items():
        time = min(repeat(func, number=100000, repeat=20))
        print('%.3f' % time, author)
    print()