3

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?

1
  • Modify your map like [list(map(lambda x: int(x) if x.isdigit() else x,a)) for a in listy] Commented Apr 20, 2018 at 2:12

3 Answers 3

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]] 
Sign up to request clarification or add additional context in comments.

1 Comment

isdigit() only recognizes unsigned int. maybe enough for op. More on that topic: stackoverflow.com/questions/1265665/…
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]] 

Comments

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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.