1

Let's say that I have a list of integer-lists:

start=[[1,2,3],[4,5,6],[7,8,9]]

And I want to convert this into:

result=[["1","2","3"],["4","5","6"],["7","8","9"]]

I could solve this issue by creating my own function. Is there a way to solve it without a custom function?

def stringify(x):
     return map(str,x)

start = [[1,2,3],[4,5,6],[7,8,9]]

result = map(stringify,start)
Larry Freeman
  • 418
  • 6
  • 19

3 Answers3

4

You can use map() in combination with list comprehension, like this:

result = [map(str, lst) for lst in start]
Delgan
  • 18,571
  • 11
  • 90
  • 141
3

To make it as pythonic as possible, I would write:

result = [[str(subitem) for subitem in sublist] for sublist in start]

IMO, it is always better to write the most readable code, and list-comprehensions are sometimes faster than map.

Community
  • 1
  • 1
DevLounge
  • 8,313
  • 3
  • 31
  • 44
1

if you know the array is regular (i.e., all rows have the same length) you can also do

result = numpy.array(start, dtype=str)

which of course however returns a numpy array, not a list.