The interconversion between datatypes is a quite useful utility and many articles have been written to perform the same. This article discusses the interconversion between a tuple of characters to individual strings. This kind of interconversion is useful in Machine Learning in which we need to give the input to train the model in a specific format. Let’s discuss certain ways in which this can be done.
Method #1: Using list comprehension + join() The list comprehension performs the task of iterating the entire list of tuples and the join function performs the task of aggregating the elements of tuples into one list.
Python3
test_list = [( 'G' , 'E' , 'E' , 'K' , 'S' ), ( 'F' , 'O' , 'R' ),
( 'G' , 'E' , 'E' , 'K' , 'S' )]
print ( "The original list is : " + str (test_list))
res = [''.join(i) for i in test_list]
print ( "The list after conversion to list of string : " + str (res))
|
OutputThe original list is : [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')]
The list after conversion to list of string : ['GEEKS', 'FOR', 'GEEKS']
Method #2: Using map() + join() The task performed by the list comprehension can be performed by the map function which can perform an extension of the logic of one tuple to all tuples in the list.
Python3
test_list = [( 'G' , 'E' , 'E' , 'K' , 'S' ), ( 'F' , 'O' , 'R' ),
( 'G' , 'E' , 'E' , 'K' , 'S' )]
print ( "The original list is : " + str (test_list))
res = list ( map (''.join, test_list))
print ( "The list after conversion to list of string : " + str (res))
|
OutputThe original list is : [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')]
The list after conversion to list of string : ['GEEKS', 'FOR', 'GEEKS']
Method: Using format specifier
Python3
l = test_list = [( 'G' , 'E' , 'E' , 'K' , 'S' ), ( 'F' , 'O' , 'R' ),( 'G' , 'E' , 'E' , 'K' , 'S' )]
x = [( '{}' * len (t)). format ( * t).strip() for t in l]
print (x)
|
Output['GEEKS', 'FOR', 'GEEKS']
Method: Using enumerate function
Python3
test_list = [( 'G' , 'E' , 'E' , 'K' , 'S' ), ( 'F' , 'O' , 'R' ),
( 'G' , 'E' , 'E' , 'K' , 'S' )]
res = [''.join(i) for a, i in enumerate (test_list)]
print ( "The list after conversion to list of string : " + str (res))
|
OutputThe list after conversion to list of string : ['GEEKS', 'FOR', 'GEEKS']
Method: Using functools.reduce method
Python
from functools import reduce
test_list = [( 'G' , 'E' , 'E' , 'K' , 'S' ), ( 'F' , 'O' , 'R' ),
( 'G' , 'E' , 'E' , 'K' , 'S' )]
print ( "The original list is : " + str (test_list))
res = reduce ( lambda a, b: a + [''.join(b)] if type (a)
! = tuple else [' '.join(a)]+[' '.join(b)], test_list)
print ( "The list after conversion to list of string : " , res)
|
OutputThe original list is : [('G', 'E', 'E', 'K', 'S'), ('F', 'O', 'R'), ('G', 'E', 'E', 'K', 'S')]
('The list after conversion to list of string : ', ['GEEKS', 'FOR', 'GEEKS'])
Please Login to comment...