Mahir Islam
Mahir Islam

Reputation: 1972

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?

Upvotes: 4

Views: 1070

Answers (3)

J. Herradez
J. Herradez

Reputation: 1

The problem with your solution is that the first items in both inner arrays are not a number so when you try to convert them it gives you that error.

You can do this if you don't know in which positions the non-numbers will be:

outerList = [['+', '1', '0'], ['-', '2', '0']]
result = []
for innerList in outerList:
  innerResult = []
  for elem in innerList:
    try:
      number = int(elem)
      innerResult.append(number)
    except Exception as e:
      innerResult.append(elem)
  result.append(innerResult)
print(result)

If it's always the first one that is not a number then you can do:

outerList = [['+', '1', '0'], ['-', '2', '0']]
result = []
for innerList in outerList:
  innerResult = []
  for i, elem in enumerate(innerList):
    if i == 0:
      innerResult.append(elem)
    else:
      innerResult.append(int(elem))
  result.append(innerResult)
print(result)

Upvotes: 0

user3483203
user3483203

Reputation: 51165

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

Upvotes: 7

Campbell McDiarmid
Campbell McDiarmid

Reputation: 494

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

Upvotes: 1

Related Questions