将数组的int值转换为字符串?

时间:2018-05-30 16:34:13

标签: python python-3.x

我有以下数组

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

我想将值从int转换为str,如下所示:

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

我该怎么做?

2 个答案:

答案 0 :(得分:0)

arr使用整数作为你的数组,你可以这样做:

list(map(lambda i: list(map(str,i)), arr))有一个班轮。

结果:

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

答案 1 :(得分:0)

以下可能有效:

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

示例用法:

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

警告:

对于名为stryng的字符串,stryng[0]stryng[539]stryng[whatever]不是字符,它们是字符串。

因此,

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

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

假设您尝试深入挖掘嵌套容器,直到找到没有__iter__方法的对象(即非容器)。假设嵌套容器中有一个字符串。然后,您将以无限递归或循环结束,因为"a"[0]可以对任何字符"a"进行迭代。具体来说,"a"有一个元素,"a"[0]"a"[0]== "a"

相关问题