我有一个包含字符串的元组的元组:

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

相关:

转换 str -> int 转换列表[str] ->列表[int]


当前回答

不要使用int(),而是使用float(),这样可以同时使用小数和整数。

其他回答

到目前为止,我同意每个人的答案,但问题是,如果你没有所有的整数,它们会崩溃。

如果你想排除非整数

T1 = (('13', '17', '18', '21', '32'),
      ('07', '11', '13', '14', '28'),
      ('01', '05', '06', '08', '15', '16'))
new_list = list(list(int(a) for a in b) for b in T1 if a.isdigit())

这只会产生实际的数字。我不使用直接的列表推导式的原因是列表推导式泄露了它们的内部变量。

Python 2的另一个函数解决方案:

from functools import partial

map(partial(map, int), T1)

Python 3会有一点混乱:

list(map(list, map(partial(map, int), T1)))

我们可以用包装器来解决这个问题

def oldmap(f, iterable):
    return list(map(f, iterable))

oldmap(partial(oldmap, int), T1)

在Python 3.5.1中,类似这样的工作:

c = input('Enter number:')
print (int(float(c)))
print (round(float(c)))

and

Enter number:  4.7
4
5

试试这个。

x = "1"

X是一个字符串,因为它周围有引号,但它里面有一个数字。

x = int(x)

因为x里面有数字1,我可以把它变成一个整数。

要查看字符串是否是数字,可以这样做。

def is_number(var):
    try:
        if var == int(var):
            return True
    except Exception:
        return False

x = "1"

y = "test"

x_test = is_number(x)

print(x_test)

它应该打印为IDLE True,因为x是一个数字。

y_test = is_number(y)

print(y_test)

它应该打印为IDLE False,因为y不是一个数字。

Python内置了函数int(string)和可选参数基。

如果你的字符串包含一个Integer值,它会将其转换为相应的Integer值。 然而,如果你有小数作为字符串,你将需要float()来转换它。

用法:

a = '22'
b = int(a)

and

if a = '22.22'
b = int(a) '''will give error, invalid literal for int().'''
b = float(a) '''will convert the string.'''