3

I have an array of longitudes and latitudes in the format:

coord = [[lat1,long2],[lat2,long2],...,[latn,longn]]

I want to convert them from degrees to radians creating two arrays, one containing longitude and one containing latitude. To do this I want to use the map function to avoid for loops, I want to do something like this:

lat_ = map(radians,coords[_][0])

Where _ is the index that changes.

1
  • I want to see if with latest python if there is a better way of doing this than the answers listed below ? Commented Oct 4, 2019 at 7:54

2 Answers 2

2

Although I would normally use a list comprehension as Karl's answer, you specifically asked about how to do it using map. The simple way is with a lambda:

lat_ = map(lambda i:radians(i[0]), l)
lon_ = map(lambda i:radians(i[1]), l)

Note that with Python 3.x this will give a generator (specifically a "map object") - but depending what you want to do with it that may be an advantage.

Sign up to request clarification or add additional context in comments.

2 Comments

I was deliberately trying in my answer to avoid giving a direct solution using map, but I suppose it would have been polite to mention lambda, yeah. :)
@KarlKnechtel It is always difficult to get the balance between giving too much and too little.
1

Normally in Python we do this with a list comprehension:

lats = [radians(coord[0]) for coord in coords]
longs = [radians(coord[1]) for coord in coords]

To translate that into map-speak, you'd need a function that encapsulates the radians(coord[0]) operation.

Alternately, you could prepare the lists of latitudes-in-degrees and longitudes-in-degrees first. The built-in function zip can do this (zip(*coords), since each list being zipped together is an argument to the function).

Keep in mind that in 3.x, both map and zip will return generators, and you'll need to explicitly convert them in order to get actual lists back (e.g. list(map(...))).

But seriously, use list comprehensions. They're the standard idiom and they're far more clear - they use square brackets to denote that a list is being created, and then in between is an actual description of the list contents in terms of the input data. It doesn't get any simpler or clearer than that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.