如何将字符串转换为整数? [英] How to convert strings into integers?

查看:64
本文介绍了如何将字符串转换为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

我尝试使用 eval 来实现它,但还没有得到任何像样的结果.

解决方案

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

<预><代码>>>>int(1") + 12

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

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

在 Python 2 中:

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

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

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

解决方案

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:

>>> int("1") + 1
2

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

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

In Python 2:

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

这篇关于如何将字符串转换为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆