Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert list of tuples of mixed data types into all string

I have this list;

List=[(1, 'John', 129L, 37L), (2, 'Tom', 231L, 23L)]

I want to convert it to look like this;

OutputList = [('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]

All the data type in the list will be turned into string. I tried [str(i) for i in List] but it did not turn out right. What is the proper way to solve this?

I am using python 2.7

like image 894
guagay_wk Avatar asked Feb 13 '23 15:02

guagay_wk


2 Answers

Using nested list comprehension (generator expression inside):

>>> lst = [(1, 'John', 129L, 37L), (2, 'Tom', 231L, 23L)]
>>> [tuple(str(x) for x in xs) for xs in lst]
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]

or using map in place of the generator expression:

>>> [tuple(map(str, xs)) for xs in lst]
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]

The above list comprehensions are similar to following nested for loop:

>>> result = []
>>> for xs in lst:
...     temp = []
...     for x in xs:
...         temp.append(str(x))
...     result.append(tuple(temp))
...
>>> result
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]
like image 137
falsetru Avatar answered Feb 17 '23 11:02

falsetru


you can also use this:

>>> lst
[(1, 'John', 129L, 37L), (2, 'Tom', 231L, 23L)]
>>> map(lambda x: tuple(map(lambda i: str(i), x)), lst)
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]

Edit: Replaced lambda i: str(i) to just str in inner map:

>>> map(lambda t: tuple(map(str, t)), lst)
[('1', 'John', '129', '37'), ('2', 'Tom', '231', '23')]
like image 37
Grijesh Chauhan Avatar answered Feb 17 '23 12:02

Grijesh Chauhan