Sometimes, while working with data, we can have a problem in which we receive mixed data and need to convert the integer elements in form of strings to integers. This kind of operation might be required in data preprocessing step. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using list comprehension + isdigit()
This is one way in which this task can be performed. In this, we check for each element of string whether it is a number using isdigit, and then converted to int if it is one. The iteration is using list comprehension.
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
res = [ int (ele) if ele.isdigit() else ele for ele in test_list]
print ( "List after converting string numbers to integers : " + str (res))
|
Output : The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #2 : Using map() + lambda + isdigit()
This task can also be performed using above functions. In this, we perform the task of iteration using map() and lambda function.
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
res = list ( map ( lambda ele : int (ele) if ele.isdigit()
else ele, test_list))
print ( "List after converting string numbers to integers : " + str (res))
|
Output : The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(n), where n is the length of the input list test_list.
Method #3 : Using isnumeric() method
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
res = []
for i in test_list:
if i.isnumeric():
res.append( int (i))
else :
res.append(i)
print ( "List after converting string numbers to integers : " + str (res))
|
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method #4 : Using try-except
Step-by-step approach :
- Initialize an empty list res.
- Use a for loop to iterate through each element of the test_list.
- Use a try-except block to check whether the current element can be converted to an integer using the int() function.
- If the conversion is successful, append the integer value to the res list using res.append(int(i)).
- If the conversion fails, simply append the original string value to the res list using res.append(i).
- Print the result list.
Below is the implementation of the above approach:
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
res = []
for i in test_list:
try :
res.append( int (i))
except :
res.append(i)
print ( "List after converting string numbers to integers : " + str (res))
|
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N)
Auxiliary Space : O(N)
Method#5: Using a for loop
Here’s the step-by-step algorithm for the approach used in this code, as well as its time and space complexity:
Algorithm:
- Initialize the original list of strings and integers.
- Initialize an empty list to store the converted integers.
- Loop through each element in the original list.
- Check if the element is a string representing an integer by using the isdigit() method.
- If the element is a string representing an integer, convert it to an integer and append it to the new list.
- If the element is not a string representing an integer, append the original element to the new list.
- Print the new list containing the converted integers.
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
int_list = []
for ele in test_list:
if ele.isdigit():
int_list.append( int (ele))
else :
int_list.append(ele)
print ( "List after converting string numbers to integers : " + str (int_list))
|
OutputList after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity:
The time complexity of this algorithm is O(n), where n is the length of the input list. This is because we loop through each element in the input list once, and each step in the loop takes constant time.
Auxiliary Space:
The space complexity of this algorithm is also O(n). We initialize an empty list of the same size as the input list to store the converted integers. This means that the space required is proportional to the size of the input list. However, the memory usage is relatively low as we are only storing integers and not creating new variables.
Method #6: Using a dictionary
This method uses a dictionary to map each digit string to its corresponding integer value. It then iterates through the list and replaces each digit string with its integer value using the get() method of the dictionary. For non-digit strings, it simply returns the original value.
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
num_dict = { str (i): i for i in range ( 10 )}
res = [num_dict.get(ele, ele) for ele in test_list]
print ( "List after converting string numbers to integers : " + str (res))
|
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity: O(n), where n is the length of the input list test_list.
Auxiliary space: O(1) because the space used by the dictionary and the output list are both proportional to the size of the input list, which is a constant factor that does not depend on the size of the input.
Method#7: Using Recursive method.
Algorithm:
- Define a function convert_to_int(lst) that takes a list as input.
- Check if the list is empty, if it is, return an empty list.
- Check if the first element of the list is a digit using the isdigit() method.
- If it is a digit, convert it to an integer using the int() function and append to a new list.
- If it is not a digit, append the original element to the new list.
- Recursively call the function with the remaining elements of the list.
- Return the new list.
Python3
def convert_to_int(lst):
if not lst:
return []
if lst[ 0 ].isdigit():
return [ int (lst[ 0 ])] + convert_to_int(lst[ 1 :])
else :
return [lst[ 0 ]] + convert_to_int(lst[ 1 :])
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
int_list = convert_to_int(test_list)
print ( "List after converting string numbers to integers : " + str (int_list))
|
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
The time complexity of this algorithm is O(n), where n is the length of the input list. This is because we iterate over each element of the list exactly once.
The auxiliary space is also O(n), as we create a new list of the same size as the input list to store the converted elements.
Method#8: reduce function from the functools module:
Algorithm:
- Import the reduce function from the functools module and define a list test_list containing string and integer values.
- Use the reduce function to iterate through each element of the list and perform the following
- If the element is a numeric string, convert it to an integer and append it to the accumulator list. Otherwise, append the element itself to the accumulator list.
- The final accumulator list is the desired result, containing integers and non-numeric strings.
Python3
from functools import reduce
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
res = reduce ( lambda acc, i: acc + [ int (i)]
if i.isnumeric() else acc + [i], test_list, [])
print ( "List after converting string numbers to integers : " + str (res))
|
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time complexity: O(n) where n is the number of elements in the list because the reduce function iterates through each element of the list once.
Space Complexity: O(n) because the accumulator list can potentially grow to the same size as the input list if all elements are numeric strings. However, in practice, the accumulator list is likely to be smaller than the input list since only a subset of elements is converted to integers.
Method#9: Using numpy:
Algorithm:
- Initialize an empty list “int_list” to store the converted integers
- Loop through each element “ele” in the original list “test_list“
- If the element is a digit, convert it to an integer and append to the “int_list“
- Otherwise, append the original element to the “int_list“
- Print the new list “int_list“
Python3
import numpy as np
import heapq
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
int_list = []
for ele in test_list:
if ele.isdigit():
int_list.append( int (ele))
else :
int_list.append(ele)
print ( "List after converting string numbers to integers : " + str (int_list))
|
Output:
The original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity: The time complexity of this algorithm is O(n), where n is the number of elements in the original list. This is because the algorithm loops through each element in the list only once.
Space Complexity: The space complexity of this algorithm is also O(n), as we are creating a new list of the same size as the original list to store the converted integers.
Method #10 : Using re.match()
Approach
- Initiate a for loop to traverse list of strings test_list
- Check whether the string is numeric using regular expression ” ^[0-9]+$ ” and method re.match()
- If yes convert the string to numeric using int() and append to output list res, if not append string as it is to res
- Display res
Python3
test_list = [ "gfg" , "1" , "is" , "6" , "best" ]
print ( "The original list : " + str (test_list))
import re
res = []
for i in test_list:
if re.match( '^[0-9]+$' , i):
res.append( int (i))
else :
res.append(i)
print ( "List after converting string numbers to integers : " + str (res))
|
OutputThe original list : ['gfg', '1', 'is', '6', 'best']
List after converting string numbers to integers : ['gfg', 1, 'is', 6, 'best']
Time Complexity : O(N) N – length of test_list
Auxiliary Space : O(N) N – length of res