问题
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(" ")).
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.
See below for more details.
>>> 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'>
>>>
Thanks in advance.
回答1:
You can use map.
myinput = "2 3"
mytuple = tuple(map(int, myinput.split(' ')))
回答2:
This seems to be a more readable way to convert a string to a tuple of integers. We use list comprehension.
myinput = "2 3 4"
mytuple = tuple(int(el) for el in myinput.split(' '))
来源:https://stackoverflow.com/questions/34168806/how-to-convert-elementsstring-to-integer-in-tuple-in-python