How do I get integers from a tuple in Python?

笑着哭i 提交于 2020-12-01 07:13:02

问题


I have a tuple with two numbers in it, I need to get both numbers. The first number is the x-coordinate, while the second is the y-coordinate. My pseudo code is my idea about how to go about it, however I'm not quite sure how to make it work.

pseudo code:

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

int1 would return 46, while int2 would return 153.


回答1:


int1, int2 = tuple



回答2:


The other way is to use array subscripts:

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

This is useful if you find you only need to access one member of the tuple at some point.




回答3:


The third way is to use the new namedtuple type:

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



回答4:


a way better way is using *:

a = (1,2,3)
b = [*a]
print(b)

it gives you a list



来源:https://stackoverflow.com/questions/3288250/how-do-i-get-integers-from-a-tuple-in-python

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