How to convert elements(string) to integer in tuple in Python

空扰寡人 提交于 2019-12-18 19:40:40

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!