jeudi 15 mai 2014

python - Convert liste des n-uplets de types de données mixtes dans toute chaîne - Stack Overflow


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




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')]



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')]


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



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')]


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')]

0 commentaires:

Enregistrer un commentaire