How do I get integers from a tuple in Python?
Asked Answered
P

5

8

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.

Perform answered 20/7, 2010 at 8:37 Comment(3)
Please don't use tuple as a variable name.Flinders
It's a good idea not to use string as a variable name either, as it's the name of a Python modulePolice
these reserved names make me want to bring sigils backCassino
V
27
int1, int2 = tuple
Verve answered 20/7, 2010 at 8:39 Comment(0)
P
26

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.

Penmanship answered 20/7, 2010 at 8:40 Comment(0)
B
6

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
Beggarweed answered 20/7, 2010 at 10:48 Comment(0)
C
0

a way better way is using *:

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

it gives you a list

Cyndi answered 18/3, 2020 at 22:28 Comment(0)
W
0

Returns a match where the string contains digits (numbers from 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)
Wormy answered 25/2, 2021 at 16:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.