0

I have 2 lists: latitude and longitude, which I'd like to format into an object in the following format:

coordinates = (-33.89419, 151.19449), (-33.66061, 151.25468), ...

How do I go about formatting this? It has to be the first latitude item with the first longitude items, and so forth. Thank you.

latitude 
 -33.89419,
 -33.66061,
 -33.89875

longitude
151.19449,
 151.25468,
 151.28507,
 151.21634

Many thanks.

Zoro
  • 420
  • 5
  • 16
  • Sort of. I'm not sure how to apply zip. It gives me: '-33.92664151.25075', '-33.89419151.19449', not (-33.89419, 151.19449), ... – Nigel Visser May 07 '21 at 04:48
  • `zip` doesn't give you that, the answer that formats its results into a string does that. `zip` actually gives you `tuple`s of the exact form requested, you just stringify them one by one and you get the desired result, e.g. `', '.join(str(pair) for pair in zip(latitude, longitude))` if you want a string, or just `list(zip(latitude, longitude))` if you want a `list` of `tuple` pairs. – ShadowRanger May 07 '21 at 05:04

2 Answers2

0

You can do:

coordinates = []
for x in range(len(latitude)):
    coordinates.append([latitude[x], longitude[x]])

Note: It has been assumed that the number of latitude coordinates is same as the number of longitude coordinates.

CoolCoder
  • 786
  • 7
  • 20
  • `zip` is definitely the more Pythonic way to go here. Iterating over ranges and indexing is both surprisingly slow and error-prone (e.g. in this case, where you just have to assume the lists are the same length, rather than stopping early as in `zip`, or providing a filler value, as in `itertools.zip_longest`). This is basically a verbose, slower, more fragile version of `coordinates = list(zip(latitude, longitude))` – ShadowRanger May 07 '21 at 05:01
0

You can combine both the latitude and longitude lists into a single list element-wise using zip. To get to the format that you wanted you can do the following

>>> str(list(zip(a,b)))[1:-1]
'(-33.89419, 151.19449), (-33.66061, 151.25468), (-33.89875, 151.28507)'
Zoro
  • 420
  • 5
  • 16
  • While using this, one must note that zip object is not subscriptable. You would always need to convert `zip` object to a `list` or `tuple` for accessing items – CoolCoder May 07 '21 at 04:52
  • @CoolCoder: Or just loop over it and use elements one at a time. Or unpack it to a varargs function (technically converts to `tuple`); a reasonable alternative if you're printing here would be `print(*zip(a, b), sep=", ")` (which avoids the need for slicing to strip off the `list` `repr`'s brackets too. – ShadowRanger May 07 '21 at 04:57