Python | Convert list of numeric string to list of integers



Method # 1: Using List Comprehension
This problem can be solved by using list comprehension as a reduction in the general cycles that we would have to go through to accomplish this particular task, repeating each the line character of each list and converting to an integer.

# Python3 demo code
# converting a list of strings to a list of integers
# using comprehension list

  
# initializing list

test_list = [[ `24` ], [ `45` ], [ ` 78` ], [ `40` ]]

 
# print original list

print ( "The original list:" + str (test_list))

 
# using comprehension list
# converting string list to list of integers

res = [[ int (i) for i in sub] for i in test_list for sub in i]

 
# print result

print ( "The list after conversion:" + str ( res))

Output:

 The original list: [[`24`], [` 45`], [`78`], [` 40`]] The list after conversion: [[2, 4], [4, 5], [7, 8], [4, 0]] 

Method # 2: Using map () + list comprehension
Problem executed in the above function can also be scaled down to include a display function that associates the conversion to integer with the function and the rest of the task is done the list comprehension function itself.

# Python3 demo code
# convert a list of strings to a list integers
# using a list comprehension + map ()

 
# initializing list

test_list = [[ `24` ], [ `45` ], [ ` 78` ] , [ `40` ]]

  
# print original list

print  ( "The original list:" + str (test_list))

 
# using comprehension list + map ()
# convert a list of strings to a list of integers

res = [ list ( map ( int , list (sub [ 0 ]))) for sub in test_list if sub]

  
# print result

print ( "The list after conversion:" + str (res))

Output:

 The original list: [[`24`], [` 45`], [`78`], [` 40`]] The list after conversion: [[2, 4], [4, 5], [7, 8], [4, 0]]