如何从 Python 中的元组中获取整数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3288250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get integers from a tuple in Python?
提问by rectangletangle
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.
我有一个包含两个数字的元组,我需要得到两个数字。第一个数字是 x 坐标,而第二个数字是 y 坐标。我的伪代码是我关于如何去做的想法,但是我不太确定如何使它工作。
pseudo code:
伪代码:
tuple = (46, 153)
string = str(tuple)
ss = string.search()
int1 = first_int(ss)
int2 = first_int(ss)
print int1
print int2
int1would return 46, while int2would return 153.
int1将返回 46,而int2将返回 153。
采纳答案by relet
int1, int2 = tuple
回答by Skilldrick
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.
如果您发现在某个时刻只需要访问元组的一个成员,这将非常有用。
回答by Tony Veijalainen
The third way is to use the new namedtuple type:
第三种方法是使用新的 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
回答by Jason
a way better way is using *:
更好的方法是使用*:
a = (1,2,3)
b = [*a]
print(b)
it gives you a list
它给你一个清单

