如何在 Python 中将元组中的元素(字符串)转换为整数 [英] How to convert elements(string) to integer in tuple in Python

查看:264
本文介绍了如何在 Python 中将元组中的元素(字符串)转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仍在学习 Python,目前正在解决一个关于 Hackerrank 的问题,我正在思考使用内置函数(tuple(input.split(" ")) 将输入(String 类型) 转换为元组.

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.

有关详细信息,请参见下文.

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'>
>>> 

提前致谢.

推荐答案

您可以使用 地图.

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

这篇关于如何在 Python 中将元组中的元素(字符串)转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆