Python - Extract digits from Tuple list
Given a list of tuples containing numbers of varying lengths, the task is to extract all unique digits present in those tuples.
Examples:
Input: list = [(15, 3), (3, 9)]
Output: [9, 5, 3, 1]Input: list = [(15, 3)]
Output: [5, 3, 1]
Using List Comprehension + Set
t = [(15, 3), (3, 9), (1, 10), (99, 2)]
temp = ''.join([str(i) for s1 in t for i in s1])
res = [int(i) for i in set(temp)]
print(res)
Output
[1, 5, 2, 3, 9, 0]
Explanation:
- [str(i) for s1 in t for i in s1]: Converts each number in all tuples to a string.
- ' '.join(...): Joins all string numbers into one continuous string.
- set(temp): Removes duplicate digits.
- [int(i) for i in set(temp)]: Converts unique string digits back to integers.
Using map() + chain.from_iterable() + set()
from itertools import chain
t = [(15, 3), (3, 9), (1, 10), (99, 2)]
s = map(str, chain.from_iterable(t))
res = {d for n in s for d in n}
print(res)
Output
{'0', '2', '9', '5', '3', '1'}
Explanation:
- chain.from_iterable(t): Flattens all tuples into a single sequence.
- map(str, ...): Converts each number to a string.
- {d for n in s for d in n}: Extracts individual digits and keeps only unique ones.
Using Regex
A compact method that converts the tuple list to a string, removes unwanted characters using regex, and extracts unique digits using set().
import re
t = [(15, 3), (3, 9), (1, 10), (99, 2)]
s = re.sub(r'[\[\]\(\), ]', '', str(t))
res = [int(i) for i in set(s)]
print(res)
Output
[1, 5, 0, 2, 9, 3]
Explanation:
- str(t): Converts tuple list to string.
- re.sub(r'[\[\]\(\), ]', '', str(t)): Removes brackets, commas, and spaces.
- set(s): Collects unique digit characters.
- int(i) for i in set(s): Converts them back to integers.
Using Nested Loops + set()
A simple approach that iterates through each tuple, collects all digits as strings, and uses set() to extract unique digits.
t = [(15, 3), (3, 9), (1, 10), (99, 2)]
s = ''
for x in t:
for y in x:
s += str(y)
res = list(map(int, set(s)))
print(res)
Output
[5, 1, 2, 3, 0, 9]
Explanation:
- s += str(y): Adds each number as a string.
- set(s): Removes duplicate digits.
- map(int, set(s)): Converts unique string digits into integers.