python - 在 python 中将 numpy ndarray 转换为字符串的更智能、更快速的方法

标签 python string numpy multidimensional-array

我将矩形的地理坐标表示为 numpy ndarray,如下所示: (每行对应一个矩形,每列包含其左下角和右上角的经纬度)

array([

  [ 116.17265886,   39.92265886,  116.1761427 ,   39.92536232],

  [ 116.20749721,   39.90373467,  116.21098105,   39.90643813],

  [ 116.21794872,   39.90373467,  116.22143255,   39.90643813]])

我想调用一个坐标转换 API,它的输入是这样一个字符串:

'lon_0,lat_0;lon_1,lat_1;lon_2,lat_2;...;lon_n,lat_n'

所以我写了一个愚蠢的迭代来将我的 ndarray 转换为所需的字符串,如下所示:

coords = ''
for i in range(0, my_rectangle.shape[0]):
    coords = coords + '{left_lon},{left_lat};{right_lon},{rigth_lat}'.format(left_lon = my_rectangle[i][0], left_lat = my_rectangle[i][1], \
                                                               right_lon = my_rectangle[i][2], rigth_lat = my_rectangle[i][3])
    if i != my_rectangle.shape[0] - 1:
        coords = coords + ';'

输出是这样的:

'116.172658863,39.9226588629;116.176142698,39.9253623188;116.207497213,39.9037346711;116.210981048,39.9064381271;116.217948718,39.9037346711;116.221432553,39.9064381271'

我想知道是否存在无需迭代(或我可以引用的一些有用文档)的更智能、更快速的方法来实现此目的?

最佳答案

让我们尝试使用函数式风格:

values = [[ 116.17265886,   39.92265886,  116.1761427 ,   39.92536232],
          [ 116.20749721,   39.90373467,  116.21098105,   39.90643813],
          [ 116.21794872,   39.90373467,  116.22143255,   39.90643813]]

def prettyPrint(coords):
    return '{0},{1};{2},{3}'.format(coords[0], coords[1], coords[2], coords[3])

asString = formating(list(map(prettyPrint,values)))
print(";".join(asString)) #edited thanks to comments

map 将函数应用于可迭代对象的每个元素。因此,您定义了应用于一个元素的过程,然后使用 map 用其结果替换每个元素。

希望你觉得它更聪明 ;)

编辑: 你也可以这样写:

asString = [prettyPrint(value) for value in values] 

关于python - 在 python 中将 numpy ndarray 转换为字符串的更智能、更快速的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26335142/

相关文章:

python - 两个单词向量之间的字符串相似度

c++ - char 类型并将 ASCII 文本重新编码为 UTF-16

python - 如何在 Python 中合并两个 json 字符串?

python - 在Python中生成3个不同的随机数

python - 提取列表中找到的子列表的索引

键中的 Python 字典键

python - 如何提取 HTML 段落的某些部分

python - 无法读取 Pandas 数据框中的嵌套 JSON

c++ - 将文本文件读入字符串数组

python - 删除包含少于 (N) 个像素的点