2010-07-20 31 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 
相關問題