Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a list of string numbers into int number in Python3?

Possible Duplicate: How to convert strings into integers in Python?

Hello guys,

I am trying to convert this string integers from a nested list to integers. This is my list:

listy = [['+', '1', '0'], ['-', '2', '0']]

I trying to convert to this:

[['+', 1, 2], ['-', 2, 0]]

This what I have tried so far, but my second line of code is taken from one of the answers in the question How to convert strings into integers in Python?

listy = [['+', '1', '0'], ['-', '2', '0']]
T2 = [list(map(int, x)) for x in listy]
print(T2)

But it gives me an error:

ValueError: invalid literal for int() with base 10: '+'

Is there any possible way to fix this in Python 3?

like image 955
Mahir Islam Avatar asked Jan 28 '23 06:01

Mahir Islam


2 Answers

You could use isdigit():

x = [['+', '1', '0'], ['-', '2', '0']]    
x = [[int(i) if i.isdigit() else i for i in j] for j in x]

Output:

[['+', 1, 0], ['-', 2, 0]]

If you want to a solution that works for signed integers as well:

x = [['+', '1', '0'], ['-', '-2', '0']]

def check_conversion(x):
  try:
    return int(x)
  except:
    return x

x = [list(map(check_conversion, i)) for i in x]

Output:

[['+', 1, 0], ['-', -2, 0]]
like image 93
user3483203 Avatar answered Jan 30 '23 20:01

user3483203


You're getting ValueError because '+' and '-' cannot be converted to a type int. So you will need to check the type and/or contents of each string that you are looking to convert. The following example checks to see if each item in a sublist contains only digits 0-9:

listy = [['+', '1', '0'], ['-', '2', '0']]
T2 = [[int(x) if x.isdigit() else x for x in sublisty] for sublisty in listy]
print(T2)
>>> [['+', 1, 0], ['-', 2, 0]]
like image 27
Campbell McDiarmid Avatar answered Jan 30 '23 20:01

Campbell McDiarmid