2010-07-20 70 views
3

我有一个包含两个数字的元组,我需要得到两个数字。第一个数字是x坐标,第二个数字是y坐标。我的伪代码是关于如何去做的我的想法,但是我不太清楚如何使它工作。如何从Python中的元组中获取整数?

伪代码:

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.

+10

请不要用'tuple'作为变量名。 – kennytm 2010-07-20 08:42:12

+7

不要使用'string'作为变量名是个好主意,因为它是Python模块的名称 – 2010-07-20 08:49:34

+1

这些保留名称使我想要带回标记 – 2010-07-20 09:01:55

回答

25
int1, int2 = tuple 
22

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

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

这很有用如果你发现你只需要在某个时候访问元组的一个成员。

6

第三种方法是使用新的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 
相关问题