-1

I have the following array

([[ 1,  1,  2,  2],
   [ 1,  1,  3,  3],
   [ 1,  1,  4,  4]])

I want to convert values from int to str, like this:

([[ '1',  '1',  '2',  '2'],
   [ '1',  '1',  '3',  '3'],
   [ '1',  '1',  '4',  '4']])

How can I do this?

jpp
  • 159,742
  • 34
  • 281
  • 339
Elmoro
  • 98
  • 1
  • 13

2 Answers2

0

arr being your array with ints, you can do:

list(map(lambda i: list(map(str,i)), arr)) with a one liner.

The result:

[['1', '1', '2', '2'], ['1', '1', '3', '3'], ['1', '1', '4', '4']]

alegria
  • 931
  • 2
  • 10
  • 25
0

The following might work:

def stringify_nested_containers(obj):
    if hasattr(obj, '__iter__') and not isinstance(obj, str):
        obj = list(obj)
        for idx in range(0, len(obj)):
            obj[idx] = stringify_nested_containers(obj[idx])
    else:
        obj = str(obj)
    return obj

Example Usage:

lyst = [
            [ 1,  1,  2,  2],
            [ 1,  1,  3,  3],
            [ 1,  1,  4,  4]
]

slyst = stringify_nested_containers(lyst)
print(slyst)
print(type(slyst[0][0]))

Warning:

For a string named stryng, stryng[0], stryng[539], or stryng[whatever] are not characters, they are strings.

Thus,

"h" == "hello world"[0]

and

"h" == "hello world"[0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0][0]

Suppose you try to dig down into nested containers until you reach to an object which does not have an __iter__ method (i.e. a non-container). Suppose there is a string in your nested container. Then you will end up in an infinite recursion or loop because "a"[0] is iterable for any character "a". Specifically "a" has one element, "a"[0] and "a"[0]== "a".

Toothpick Anemone
  • 4,290
  • 2
  • 20
  • 42