Reputation: 490
I have my geographical coordinates of rectangles represented as numpy ndarray like this: (each row corresponds to a rectangle and each column contains its lower left and upper right longitudes and latitudes)
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]])
I want to call a coordinate-converting API whose input is a string like this:
'lon_0,lat_0;lon_1,lat_1;lon_2,lat_2;...;lon_n,lat_n'
So I wrote a stupid iteration to convert my ndarray to the required string like this:
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 + ';'
And the output is like this:
'116.172658863,39.9226588629;116.176142698,39.9253623188;116.207497213,39.9037346711;116.210981048,39.9064381271;116.217948718,39.9037346711;116.221432553,39.9064381271'
I'm wondering whether there exists a smarter & faster approach achieving this without iteration(or some helpful documentation I could refer to)?
Upvotes: 3
Views: 1423
Reputation: 1571
Let's try using functional style:
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 apply a function to each element of an iterable. So you define the process to apply on one element, and then using map replace each element by its result.
Hope you find it smarter ;)
Edit : You can also write it like this :
asString = [prettyPrint(value) for value in values]
Upvotes: 3