在Python中,如何从元组中获取整数?

2024-06-28 18:52:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含两个数字的元组,我需要得到两个数字。第一个数字是x坐标,第二个是y坐标。我的伪代码是关于如何实现它的想法,但是我不太确定如何使它工作。

伪代码:

tuple = (46, 153)
string = str(tuple)
ss = string.search()
int1 = first_int(ss) 
int2 = first_int(ss) 
print int1
print int2

int1将返回46,而int2将返回153。


Tags: 代码searchstring数字ssintfirst元组
3条回答
int1, int2 = tuple

第三种方法是使用新的namedtuple类型:

from collections import namedtuple
Coordinates = namedtuple('Coordinates','x,y')
coords = Coordinates(46,153)
print coords
print 'x coordinate is:',coords.x,'y coordinate is:',coords.y

另一种方法是使用数组下标:

int1 = tuple[0]
int2 = tuple[1]

如果您发现在某个点上只需要访问元组的一个成员,那么这非常有用。

相关问题 更多 >