如何在Python中将字符串转换为整数?

如何在Python中将字符串转换为整数?

问题描述:

我有一个来自MySQL查询的元组元组,如下所示:

I have a tuple of tuples from a MySQL query like this:

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))

我想将所有字符串元素转换为整数并将它们放回列表列表中:

I'd like to convert all the string elements into integers and put them back into a list of lists:

T2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]

我试图用 eval 来实现它,但还没有得到任何不错的结果。

I tried to achieve it with eval but didn't get any decent result yet.

int() 是用于将字符串转换为整数值的Python标准内置函数。您使用包含数字作为参数的字符串调用它,并返回转换为整数的数字:

int() is the Python standard built-in function to convert a string into an integer value. You call it with a string containing a number as the argument, and it returns the number converted to an integer:

print (int("1") + 1)

以上打印 2

如果您知道列表的结构,T1(它只包含列表,只有一个级别),您可以在Python 2中执行此操作:

If you know the structure of your list, T1 (that it simply contains lists, only one level), you could do this in Python 2:

T2 = [map(int, x) for x in T1]

在Python 3中:

In Python 3:

T2 = [list(map(int, x)) for x in T1]