[英]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.