繁体   English   中英

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

[英]How do I get integers from a tuple in 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。

int1, int2 = tuple

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

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

如果您发现在某个时刻只需要访问元组的一个成员,这将非常有用。

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

更好的方法是使用*

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

它给你一个清单

返回字符串包含数字(0-9 之间的数字)的匹配项

import re
tl = [(1, 11), (5, 9) , (6,3)]

list1 = re.findall(r'\d+',str(tl))

tlstr = ''.join(list1)

num = list(set(tlstr))
print(num)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM