python 在python中从字符串列表列表转换为整数列表列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2166577/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:57:22  来源:igfitidea点击:

Casting from list of lists of strings to list of lists of ints in python

python

提问by Chris

I'm reading some numbers from a data source that represent xy 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:

我正在从数据源中读取一些数字,这些数字代表我将用于 TSP 式问题的 xy 坐标。我是 python 的新手,所以我试图充分利用列表。阅读并解析数据后,我得到了一个字符串列表,如下所示:

[['565.0', '575.0'], ['1215.0', '245.0'], ...yougetthepoint... ['1740.0', '245.0']]

[['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'

ValueError:int() 的无效文字,基数为 10:'565.0'

The decimal seems to be causing issues.

小数点似乎引起了问题。

回答by Max Shawabkeh

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]