我仍在学习 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/