Casting from a list of lists of strings to list of lists of ints in Python

Question:

I’m reading some numbers from a data source that represent x- and y-coordinates that I’ll be using for a TSP-esque problem. I’m new to Python, so I’m trying to make the most of lists. After reading and parsing through the data, I’m left with a list of string lists that looks like this:

[[‘565.0’, ‘575.0’], [‘1215.0’,
‘245.0’], …yougetthepoint…
[‘1740.0’, ‘245.0’]]

I would rather be dealing with integer points. How can I transform these lists containing strings to lists containing ints? They don’t seem to be casting nicely, as I get this error:

ValueError: invalid literal for int()
with base 10: ‘565.0’

The decimal seems to be causing issues.

Asked By: Chris

||

Answers:

x = [['565.0', '575.0'], ['1215.0', '245.0'], ['1740.0', '245.0']]
x = [[int(float(j)) for j in i] for i in x]
Answered By: Max Shawabkeh
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.