如何在Python中将元素(字符串)转换为元组中的整数 [英] How to convert elements(string) to integer in tuple in Python
问题描述
我仍在学习 Python,目前正在解决我正在思考的 Hackerrank 上的一个问题使用内置函数(tuple(input.split(" ")))将输入(字符串类型)转换为元组.
I am still learning Python and currently solving a question on Hackerrank where I am thinking of converting input(String type) to tuple by using built-in function(tuple(input.split(" ")).
比如myinput = "2 3",我想把它转换成元组,比如(2,3).但是,如果我这样做,它当然会给我一个字符串类型的元组,例如('2','3').我知道有很多方法可以解决这个问题,但我想知道如何以最有效的方式将元组中的元素(str)转换为整数(在 Python 中).
For example, myinput = "2 3", and I want to convert it to tuple,such as (2,3). However,if I do that, it will, of course, give me a tuple with String type, like ('2', '3'). I know that there are a lot of ways to solve the problem, but I'd like to know how to convert elements(str) in tuple to integer(in Python) in most efficient way.
详情请见下文.
>>> 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'>
>>>
提前致谢.
推荐答案
你可以使用 地图.
myinput = "2 3"
mytuple = tuple(map(int, myinput.split(' ')))
这篇关于如何在Python中将元素(字符串)转换为元组中的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!