Thursday, December 26, 2024
Google search engine
HomeLanguagesPython | Convert numeric String to integers in mixed List

Python | Convert numeric String to integers in mixed List

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




# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# using list comprehension + isdigit()
 
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Convert String numbers to integers in mixed List
# using list comprehension + isdigit()
res = [int(ele) if ele.isdigit() else ele for ele in test_list]
 
# printing result
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




# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# using map() + lambda + isdigit()
 
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Convert String numbers to integers in mixed List
# using map() + lambda + isdigit()
res = list(map(lambda ele : int(ele) if ele.isdigit()
          else ele, test_list))
 
# printing result
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




# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
 
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Convert String numbers to integers in mixed List
res = []
for i in test_list:
    if i.isnumeric():
        res.append(int(i))
    else:
        res.append(i)
# printing result
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 #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




#Python3 code to demonstrate working of
#Convert String numbers to integers in mixed List
#using try-except
#initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
#printing original list
print("The original list : " + str(test_list))
 
#Convert String numbers to integers in mixed List
res = []
for i in test_list:
  try:
    res.append(int(i))
  except:
    res.append(i)
 
#printing result
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#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:

  1. Initialize the original list of strings and integers.
  2. Initialize an empty list to store the converted integers.
  3. Loop through each element in the original list.
  4. Check if the element is a string representing an integer by using the isdigit() method.
  5. If the element is a string representing an integer, convert it to an integer and append it to the new list.
  6. If the element is not a string representing an integer, append the original element to the new list.
  7. Print the new list containing the converted integers.

Python3




# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# create a new list to store the converted integers
int_list = []
 
# loop through each element in the original list
for ele in test_list:
    # if the element is a digit, convert it to an integer and append to the new list
    if ele.isdigit():
        int_list.append(int(ele))
    # otherwise, append the original element to the new list
    else:
        int_list.append(ele)
 
# print the new list
print("List after converting string numbers to integers : " + str(int_list))
#This code is contributed by Vinay Pinjala.#This code is contributed by Vinay Pinjala.


Output

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 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




# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
# using dictionary
 
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Convert String numbers to integers in mixed List
# using dictionary
num_dict = {str(i): i for i in range(10)}
res = [num_dict.get(ele, ele) for ele in test_list]
 
# printing result
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(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:

  1. Define a function convert_to_int(lst) that takes a list as input.
  2. Check if the list is empty, if it is, return an empty list.
  3. Check if the first element of the list is a digit using the isdigit() method.
  4. If it is a digit, convert it to an integer using the int() function and append to a new list.
  5. If it is not a digit, append the original element to the new list.
  6. Recursively call the function with the remaining elements of the list.
  7. Return the new list.

Python3




def convert_to_int(lst):
    """
    Recursive function to convert string numbers to integers in a list.
    """
    # base case: empty list
    if not lst:
        return []
 
    # if the first element is a digit, convert it to an integer and append to the new list
    if lst[0].isdigit():
        return [int(lst[0])] + convert_to_int(lst[1:])
 
    # otherwise, append the original element to the new list
    else:
        return [lst[0]] + convert_to_int(lst[1:])
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# call recursive function to convert string numbers to integers
int_list = convert_to_int(test_list)
 
# print the new list
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']

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:

  1. Import the reduce function from the functools module and define a list test_list containing string and integer values.
  2. Use the reduce function to iterate through each element of the list and perform the following
  3. 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.
  4. The final accumulator list is the desired result, containing integers and non-numeric strings.

Python3




# Python program for the above approach
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))
 
# This code is contributed by Rayudu.


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 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:

  1. Initialize an empty list “int_list” to store the converted integers
  2. 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
  3. Print the new list “int_list

Python3




import numpy as np
import heapq
 
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# create a new list to store the
# converted integers
int_list = []
 
# loop through each element in the
# original list
for ele in test_list:
 
    # if the element is a digit, convert it
    # to an integer and append to the new list
    if ele.isdigit():
        int_list.append(int(ele))
 
    # otherwise, append the original
    # element to the new list
    else:
        int_list.append(ele)
 
# print the new list
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

  1. Initiate a for loop to traverse list of strings test_list
  2. Check whether the string is numeric using regular expression ” ^[0-9]+$ ” and method re.match()
  3. If yes convert the string to numeric using int() and append to output list res, if not append string as it is to res
  4. Display res

Python3




# Python3 code to demonstrate working of
# Convert String numbers to integers in mixed List
 
 
# initialize list
test_list = ["gfg", "1", "is", "6", "best"]
 
# printing original list
print("The original list : " + str(test_list))
 
# Convert String numbers to integers in mixed List
import re
res=[]
for i in test_list:
    if re.match('^[0-9]+$', i):
        res.append(int(i))
    else:
        res.append(i)
# printing result
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) N – length of test_list

Auxiliary Space : O(N) N – length of res

RELATED ARTICLES

Most Popular

Recent Comments