4

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?

Mahir Islam
  • 1,941
  • 2
  • 12
  • 33

3 Answers3

7

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]]
user3483203
  • 50,081
  • 9
  • 65
  • 94
  • isdigit() only recognizes unsigned int. maybe enough for op. More on that topic: https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except – greedy52 Apr 20 '18 at 02:11
1

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

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)