使用 map() 将整数列表转换为字符串

Rid*_*azi 2 python dictionary type-conversion

我不明白为什么 python 不允许我使用 map() 函数将整数列表更改为字符串列表。当我尝试在 python shell 中执行它时它工作正常,但当我在脚本中尝试时却没有,我真的很困惑为什么会发生这种情况。这是我的脚本代码:

def DashInsert(str):

    list_int = map(int, list(str))
    list_str = map(str, list_int)

    return list_str 
Run Code Online (Sandbox Code Playgroud)

此外,我知道如果列表已经作为字符串输入,我不需要将列表更改回字符串,但我很好奇为什么 Python 在我将它转换为整数列表后不会让我更改列表。我不断收到“str object is not callable”错误。

Jon*_*nts 5

当你这样做时:

def DashInsert(str):
Run Code Online (Sandbox Code Playgroud)

您正在str为 的范围隐藏内置函数DashInsert,因此当您尝试使用list_str = map(str, list_int)它时将无法按预期工作,因为str它不再是 Python 的内置str函数,它等于您传递给函数的对象。考虑重命名它,例如:

def DashInsert(text):
    list_int = map(int, list(text))
    list_str = map(str, list_int)
    return list_str
Run Code Online (Sandbox Code Playgroud)