Friday, December 27, 2024
Google search engine
HomeLanguagesPython – Filter float strings from String list

Python – Filter float strings from String list

Sometimes, while working with Python list, we can have a problem in which we need to separate the float values from valid strings. But problem arises when float values are in form of strings. Let’s discuss certain ways in which this task can be performed. 

Method #1 : Using loop + Exception Handling The combination of above functionalities can be used to perform this task. In this, we loop through each element and try to convert each string into float value, if it’s a success, means it’s a float, else it raises a ValueError and we can get desired string. 

Python3




# Python3 code to demonstrate working of
# Filter float strings from String list
# using loop + Exception Handling
 
# initialize list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# printing original list
print("The original list : " + str(test_list))
 
# Filter float strings from String list
# using loop + Exception Handling
res = []
for ele in test_list:
    try:
        float(ele)
    except ValueError:
        res.append(ele)
 
# printing result
print("String list after filtering floats : " + str(res))


Output : 

The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Time complexity: O(n), where n is the length of the list “test_list”.
Auxiliary Space: O(n), where n is the length of the list “res”.

Method #2 : Using regex + list comprehension The combination of above functionalities can perform this task. In this, we perform the task of filtering using regex created and list comprehension is used to iterate over the list and apply the filter. 

Python3




# Python3 code to demonstrate working of
# Filter float strings from String list
# using regex + list comprehension
import re
 
# initialize list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# printing original list
print("The original list : " + str(test_list))
 
# Filter float strings from String list
# using regex + list comprehension
temp = re.compile(r'\d+(?:\.\d*)')
res = [ele for ele in test_list if not temp.match(ele)]
 
# printing result
print("String list after filtering floats : " + str(res))


Output : 

The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Time Complexity: O(n), where n is the length of the input list test_list.
Auxiliary Space: O(m), where m is the number of float strings in the input list.

Method #3 : Using filter() + lambda function
The filter() function can be used to filter elements in a list based on a certain condition. In this method, we use a lambda function to check if a string can be converted to a float or not. If it can’t be converted, it means it is a valid string.

Python3




# initialize list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
   
# printing original list
print("The original list : " + str(test_list))
   
# Filter float strings from String list
# using filter() + lambda function
res = list(filter(lambda x: not x.replace('.','',1).isdigit(), test_list))
   
# printing result
print("String list after filtering floats : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output

The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Time complexity: O(n)
Auxiliary Space: O(n)

Method #4 : Using isnumeric() and replace() methods

Python3




# Python3 code to demonstrate working of
# Filter float strings from String list
 
 
# initialize list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# printing original list
print("The original list : " + str(test_list))
 
# Filter float strings from String list
res=[]
for i in test_list:
    x=i.replace(".","")
    if(not x.isnumeric()):
        res.append(i)
 
# printing result
print("String list after filtering floats : " + str(res))


Output

The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Time complexity: O(n)
Auxiliary Space: O(n)

Method 5: Using a list comprehension

 This approach involves iterating over each element in the list and checking if it is a float value using the “try-except” block, and then returning only the non-float elements in a new list.

Python3




# initialize list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# printing original list
print("The original list : " + str(test_list))
 
# Filter float strings from String list
# using list comprehension
res = [x for x in test_list if not isinstance(
    x, str) or not x.replace('.', '', 1).isdigit()]
 
# printing result
print("String list after filtering floats : " + str(res))


Output

The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Time complexity: O(n)
Auxiliary Space: O(n)

Method #6: Using map() and filter() with a lambda function

In this method, we will use the map() function to convert each element of the list to a float and then use the filter() function to keep only the non-float elements using a lambda function.

Here are the steps for this approach:

  • Define the input list.
  • Define a lambda function that checks if a given string can be converted to a float or not.
  • Use the map() function to convert each element of the input list to a float.
  • Use the filter() function with the lambda function to keep only the non-float elements.
  • Convert the filtered elements to a list.Print the filtered list.
  •  

Python3




# Python3 code to demonstrate working of
# Filter float strings from String list
# using map() and filter() with a lambda function
 
# define input list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# define lambda function to check if a string can be converted to a float
is_float = lambda x: isinstance(x, float)
 
# use map() function to convert each element to a float
float_list = list(map(lambda x: float(x) if '.' in x else x, test_list))
 
# use filter() function with lambda function to keep only non-float elements
filtered_list = list(filter(lambda x: not is_float(x), float_list))
 
# print the filtered list
print("String list after filtering floats : " + str(filtered_list))


Output

String list after filtering floats : ['gfg', 'is', 'best']

Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(n), where n is the length of the input list.

Method #7: Using the isinstance() function and list comprehension

Use list comprehension to convert each element in the input list to a float (if possible) or leave it as a string
Use the isinstance() function to filter out the float elements and store the remaining string elements in a new list
Print the filtered list

Python3




# Python3 code to demonstrate working of
# Filter float strings from String list
# using isinstance() function and list comprehension
 
# define input list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# use list comprehension to convert each element in the input list to a float (if possible) or leave it as a string
converted_list = [float(i) if "." in i else i for i in test_list]
 
# use the isinstance() function to filter out the float elements and store the remaining string elements in a new list
filtered_list = [element for element in converted_list if not isinstance(element, float)]
 
# print the filtered list
print("String list after filtering floats : " + str(filtered_list))


Output

String list after filtering floats : ['gfg', 'is', 'best']

Time complexity: O(n)
Auxiliary space: O(n)

Method #8: Using reduce():

Algorithm:

  1. Define a regular expression pattern to match floating-point numbers using re.compile method.
  2. Use list comprehension to iterate over each element of the test_list.
  3. Check if the element matches the pattern using re.match method.
  4. If it does not match, add it to the result list.
  5. Print the result list.

Python3




import re
from functools import reduce
 
# initialize list
test_list = ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
 
# printing original list
print("The original list : " + str(test_list))
 
# Filter float strings from String list using reduce
temp = re.compile(r'\d+(?:\.\d*)')
res = reduce(lambda acc, cur: acc + [cur] if not temp.match(cur) else acc, test_list, [])
 
# printing result
print("String list after filtering floats : " + str(res))
#This code is contributed by Rayudu.


Output

The original list : ['gfg', '45.45', 'is', '87.5', 'best', '90.34']
String list after filtering floats : ['gfg', 'is', 'best']

Time Complexity:
The time complexity of this algorithm is O(n), where n is the length of the input list. The regex pattern matching is done in linear time, and the list comprehension also takes linear time.

Space Complexity:
The space complexity of this algorithm is O(n), where n is the length of the input list. The result list can contain all the elements of the input list if none of them match the regex pattern.

RELATED ARTICLES

Most Popular

Recent Comments