Python – Extract digits from Tuple list
Sometimes, while working with Python lists, we can have a problem in which we need to perform extraction of all the digits from tuple list. This kind of problem can find its application in data domains and day-day programming. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [(15, 3), (3, 9)]
Output : [9, 5, 3, 1]Input : test_list = [(15, 3)]
Output : [5, 3, 1]
Method #1: Using map() + chain.from_iterable() + set() + loop
The combination of above functions can be used to solve this problem. In this, we perform the task of flattening list using chain.from_iterable(), and then the digits are extracted using brute method. set() is used to remove duplicate digits.
Python3
# Python3 code to demonstrate working of# Extract digits from Tuple list# Using map() + chain.from_iterable() + set() + loopfrom itertools import chain# initializing listtest_list = [(15, 3), (3, 9), (1, 10), (99, 2)]# printing original listprint("The original list is : " + str(test_list))# Extract digits from Tuple list# Using map() + chain.from_iterable() + set() + looptemp = map(lambda ele: str(ele), chain.from_iterable(test_list))res = set()for sub in temp: for ele in sub: res.add(ele)# printing resultprint("The extracted digits : " + str(res)) |
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)]
The extracted digits : {'1', '0', '3', '2', '9', '5'}Method #2: Using regex expression
This is yet another way in which this task can be performed. In this, an appropriate regex expression is used to extract the required unique digits.
Python3
# Python3 code to demonstrate working of# Extract digits from Tuple list# Using regex expressionimport re# initializing listtest_list = [(15, 3), (3, 9), (1, 10), (99, 2)]# printing original listprint("The original list is : " + str(test_list))# Extract digits from Tuple list# Using regex expressiontemp = re.sub(r'[\[\]\(\), ]', '', str(test_list))res = [int(ele) for ele in set(temp)]# printing resultprint("The extracted digits : " + str(res)) |
The original list is : [(15, 3), (3, 9), (1, 10), (99, 2)] The extracted digits : [5, 9, 2, 0, 1, 3]
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course



