python-3.x - 如何在 Python 中将元组中的元素(字符串)转换为整数

标签 python-3.x tuples

我仍在学习 Python,目前正在解决 Hackerrank 上的一个问题我正在考虑使用内置函数(tuple(input.split(“”))将输入(字符串类型)转换为元组。

比如myinput = "2 3",我想把它转换成元组,比如(2,3)。但是,如果我这样做,它当然会给我一个字符串类型的元组,例如 ('2', '3')。我知道有很多方法可以解决这个问题,但我想知道如何以最有效的方式将元组中的元素(str)转换为整数(在 Python 中)。

请参阅下面的更多细节。

>>> myinput = "2 3"
>>> temp = myinput.split()
>>> print(temp)
['2', '3']
>>> mytuple = tuple(myinput)
>>> print(mytuple)
('2', ' ', '3')
>>> mytuple = tuple(myinput.split(" "))
>>> mytuple
('2', '3')
>>> type(mytuple)
<class 'tuple'>
>>> type(mytuple[0])
<class 'str'>
>>> 

提前致谢。

最佳答案

您可以使用 map .

myinput = "2 3"
mytuple = tuple(map(int, myinput.split(' ')))

关于python-3.x - 如何在 Python 中将元组中的元素(字符串)转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34168806/

相关文章:

scala - 将元组转换为具有默认值的案例类

python - 如何舍入python中的两位有效数字?

python - 从文本文件中读取列表的元组作为元组,而不是字符串 - Python

python - 访问具有可变长度的元组列表的元素并以相同的格式保存输出

list - 将 3 个列表压缩成一个元组 - Erlang

Python:三重双引号字符串格式

python-3.x - 检测黑白文档上的图章形状

python - random.sample 中使用的常数的证明

mysql - 导入错误: No module named 'MySQLdb'

tuples - 你可以给元组类型起别名吗?