Python | Convert location coordinates to tuple
Last Updated :
15 May, 2023
Sometimes, while working with locations, we need a lot of data which has location points in form of latitudes and longitudes. These can be in form of a string and we desire to get tuple versions of same. Let's discuss certain ways in which this task can be performed.
Method #1 :
Using tuple() + float() + split() + map() The combination of above functions can be used to perform this task. In this, we first split the two parts of coordinates into a list, apply float function to each of them using float() and map() and lastly it is converted to tuple using tuple().
Python3
# Python3 code to demonstrate working of
# Convert location coordinates to tuple
# Using tuple() + float() + split() + map()
# Initializing string
test_str = "44.6463, -49.583"
# printing original string
print("The original string is : " + str(test_str))
# Convert location coordinates to tuple
# Using tuple() + float() + split() + map()
res = tuple(map(float, test_str.split(', ')))
# printing result
print("The coordinates after conversion to tuple are : " + str(res))
Output : The original string is : 44.6463, -49.583
The coordinates after conversion to tuple are : (44.6463, -49.583)
Method #2 :
Using eval() This is the one-liner and recommended method to perform this particular task. In this, the eval(), internally detects the string and converts to floating point number separated as tuple elements.
Python3
# Python3 code to demonstrate working of
# Convert location coordinates to tuple
# Using eval()
# Initializing string
test_str = "44.6463, -49.583"
# printing original string
print("The original string is : " + str(test_str))
# Convert location coordinates to tuple
# Using eval()
res = eval(test_str)
# printing result
print("The coordinates after conversion to tuple are : " + str(res))
Output : The original string is : 44.6463, -49.583
The coordinates after conversion to tuple are : (44.6463, -49.583)
Method #3: Using regular expression
Approach
using regular expressions to match the latitude and longitude values in the original string. We then convert the matched strings to floats and create a tuple with the two values.
Algorithm
1. Import the re module.
2. Use a regular expression to match the latitude and longitude values in the original string.
3. Convert the matched latitude and longitude strings to floats.
4. Create a tuple with the latitude and longitude floats.
5. Return the tuple.
Python3
import re
def convert_coordinates(coordinates_str):
lat_str, long_str = re.findall(r'[-+]?\d*\.\d+|\d+', coordinates_str)
lat_float = float(lat_str)
long_float = float(long_str)
return (lat_float, long_float)
coordinates_str = "44.6463, -49.583"
print(convert_coordinates(coordinates_str))
Time complexity: O(1)
Auxiliary Space: O(1)
Method 4 : using a generator expression:
step-by-step approach
Initialize a string variable test_str with the value "44.6463, -49.583".
Use the split() method with ', ' as the delimiter to split the test_str string into a list of two string values, "44.6463" and "-49.583".
Use a generator expression to loop through the list of string values and convert each string value to a float.
Use the tuple() constructor to create a tuple of the two floating-point numbers.
Assign the tuple of floating-point numbers to the variable coordinates.
Print the message "The coordinates after conversion to tuple are :" along with the value of the coordinates variable.
Python3
# Initializing string
test_str = "44.6463, -49.583"
# Using a generator expression to convert the coordinates to a tuple
coordinates = tuple(float(coord) for coord in test_str.split(', '))
# Printing the result
print("The coordinates after conversion to tuple are :", coordinates)
OutputThe coordinates after conversion to tuple are : (44.6463, -49.583)
Time complexity of O(n), where n is the length of the input string.
The auxiliary space complexity is O(n), as it creates a tuple of n floating-point numbers.
Method 5: using numpy:
- Import the numpy library.
- Initialize a string variable test_str with a string value.
- Print the original string.
- Use the numpy fromstring() method to convert the string to a numpy array.
- Split the string on the comma delimiter, and pass the resulting list to the fromstring() method.
- Set the dtype parameter of the fromstring() method to float to ensure that the array values are treated as floating-point numbers.
- Print the resulting numpy array.
Python3
import numpy as np
# input string
test_str = "44.6463, -49.583"
# convert string to 1D numpy array of float values
arr = np.fromstring(test_str, sep=", ", dtype=float)
# reshape array to a 2D array of shape (1, 2)
res = arr.reshape((1, 2))
# print result
print("The coordinates after conversion to tuple are:", res)
#This code is contributed by Pushpa.
Output:
The coordinates after conversion to tuple are: [[ 44.6463 -49.583 ]]
Time complexity: O(n), where n is the length of the string being converted to a numpy array.
Space complexity: O(n), where n is the length of the string being converted to a numpy array. This is because the resulting numpy array will take up space in memory proportional to the length of the string.
Similar Reads
Convert List to Tuple in Python The task of converting a list to a tuple in Python involves transforming a mutable data structure list into an immutable one tuple. Using tuple()The most straightforward and efficient method to convert a list into a tuple is by using the built-in tuple(). This method directly takes any iterable like
2 min read
Convert Dictionary to List of Tuples - Python Converting a dictionary into a list of tuples involves transforming each key-value pair into a tuple, where the key is the first element and the corresponding value is the second. For example, given a dictionary d = {'a': 1, 'b': 2, 'c': 3}, the expected output after conversion is [('a', 1), ('b', 2
3 min read
Python | Convert Integral list to tuple list Sometimes, while working with data, we can have a problem in which we need to perform type of interconversions of data. There can be a problem in which we may need to convert integral list elements to single element tuples. Let's discuss certain ways in which this task can be performed. Method #1 :
3 min read
Convert List of Dictionary to Tuple list Python Given a list of dictionaries, write a Python code to convert the list of dictionaries into a list of tuples.Examples: Input: [{'a':[1, 2, 3], 'b':[4, 5, 6]}, {'c':[7, 8, 9], 'd':[10, 11, 12]}] Output: [('b', 4, 5, 6), ('a', 1, 2, 3), ('d', 10, 11, 12), ('c', 7, 8, 9)] Below are various methods to co
5 min read
Python | Convert list to indexed tuple list Sometimes, while working with Python lists, we can have a problem in which we need to convert a list to tuple. This kind of problem have been dealt with before. But sometimes, we have it's variation in which we need to assign the index of the element along with element as a tuple. Let's discuss cert
3 min read
Convert Tuple to Json Array in Python Python's versatility as a programming language extends to its rich data structures, including tuples and JSON. JSON, abbreviation for JavaScript Object Notation, is a lightweight data format used for representing structured data. Moreover, it is a syntax for storing and exchanging data. In this arti
3 min read
Python | Convert tuple to float value Sometimes, while working with tuple, we can have a problem in which, we need to convert a tuple to floating-point number in which first element represents integer part and next element represents a decimal part. Let's discuss certain way in which this can be achieved. Method : Using join() + float()
3 min read
Convert List of Tuples To Multiple Lists in Python When working with data in Python, it's common to encounter situations where we need to convert a list of tuples into separate lists. For example, if we have a list of tuples where each tuple represents a pair of related data points, we may want to split this into individual lists for easier processi
3 min read
Python | Convert list of tuples to list of list Converting list of tuples to list of lists in Python is a task where each tuple is transformed into list while preserving its elements. This operation is commonly used when we need to modify or work with the data in list format instead of tuples.Using numpyNumPy makes it easy to convert a list of tu
3 min read
Python | Convert list of tuples into list In Python we often need to convert a list of tuples into a flat list, especially when we work with datasets or nested structures. In this article, we will explore various methods to Convert a list of tuples into a list. Using itertools.chain() itertools.chain() is the most efficient way to flatten a
3 min read