Sometimes, while working with data, we could be dealing with numbers, that are in decimal and not integers. This is a general case in the data science domain. Let’s discuss how to resolve a problem in which we may have a comma-separated float number and we need to convert it to a float list.
Method #1 : Using list comprehension + split() + float()
A combination of the above methods can be used to perform this task. In this, we convert the String to a string list using split and then convert the string to float using float().
Python3
test_str = "3.44, 7.8, 9.12, 100.2, 6.50"
print ( "The original string is : " + test_str)
res = [ float (idx) for idx in test_str.split( ', ' )]
print ( "The float list is : " + str (res))
|
Output : The original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]
Time complexity: O(n), where n is the length of the input string.
Auxiliary space complexity: O(n), where n is the length of the input string.
Method #2 : Using map() + split() + float()
The combination of the above functions can also be used to solve this problem. In this, we perform the task of extending logic to the entire list using map(), the rest all the functionalities are performed as the above method.
Python3
test_str = "3.44, 7.8, 9.12, 100.2, 6.50"
print ( "The original string is : " + test_str)
res = list ( map ( float , test_str.split( ', ' )))
print ( "The float list is : " + str (res))
|
Output : The original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]
Time Complexity: O(N)
Auxiliary Space: O(N)
Method #3: Using ast.literal_eval()
The ast.literal_eval() function can also be used to convert a string of comma-separated float numbers to a float list. This function safely evaluates a string as a literal expression and returns the value.
Python3
import ast
test_str = "3.44, 7.8, 9.12, 100.2, 6.50"
print ( "The original string is : " + test_str)
res = ast.literal_eval( "[" + test_str + "]" )
print ( "The float list is : " + str (res))
|
OutputThe original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]
Time complexity: O(n)
Auxiliary Space: O(n)
Method #4: Using for loop and append() method
Python3
test_str = "3.44, 7.8, 9.12, 100.2, 6.50"
print ( "The original string is : " + test_str)
res = []
for elem in test_str.split( ', ' ):
res.append( float (elem))
print ( "The float list is : " + str (res))
|
OutputThe original string is : 3.44, 7.8, 9.12, 100.2, 6.50
The float list is : [3.44, 7.8, 9.12, 100.2, 6.5]
Time complexity: O(n), where n is the number of elements in the input string.
Auxiliary space: O(n), where n is the number of elements in the input string, as we need to store the float values in a list.