Program to extract digits from the given tuple using Python

Introduction

The task is to extract all the digits from the tuple. 

Program to extract digits from the given tuple using Python

Program

Approach 1

import re
ip_list = [(1, 2), (83, 65), (74,11), (89, 7)]
print("The given list is :" + str(ip_list))
# Using regular expression
re_exp = re.sub(r'[\[\]\(\), ]', '' , str(ip_list))
output = [int(i) for i in set(re_exp)]
print("The output tuple is: "+ str(output))

Output:

Program to extract digits from the given tuple using Python Output 1

Approach 2

from itertools import chain
ip_list = [(1, 2), (83, 65), (74,11), (89, 7)]
print("The original list is :" + str(ip_list))
# Using map() + chain.from_iterable() + set()
temp = map(lambda i: str(i), chain.from_iterable(ip_list))
output = set()
for ele in temp:
    for ele in ele:
        output.add(ele)
print("The output tuple is: "+ str(output))

 

Output:

Program to extract digits from the given tuple using Python Output 2

Explanation

In first approach, we have used regression expression to extract all the digits from the tuple. The appropriate regression expression is provided to extract the unique digits of the tuple.

In second approach, we have used map(), chain.from_iterable() and set() functions to achieve our task. The lambda and chain.from_iterable() is used to flatten the elements and set() function removes the duplicate digits and prints the unique digits of the tuple.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.