python - 如何将数字列表转换为字符串?

标签 python

我想做的是获取一个给定的列表:
numlist_1: [3, 5, 4, 2, 5, 5]
并使用此函数将其转换为字符串

def to_string(my_list, sep=', '):
    newstring = ''
    count = 0
    for string in my_list:
        if (length(my_list)-1) == count:
            newstring += string
        else:
            newstring += string + sep
        count += 1

return newstring  

所需的输出显示为:
to_string 测试 列表是:3、5、4、2、5、5 列表是:3 - 5 - 4 - 2 - 5 - 5

但是,我收到一个错误提示
类型错误:+ 不支持的操作数类型:“int”和“str”

我认为这是因为打印语句之一是
print('列表是:', list_function.to_string(num_list1, sep=' - '))
并且分隔符与函数中给出的分隔符​​不同,但我希望能够伴随 ', ' 和 '-' 分隔符,因为我有另一个列表,它使用与 ', ' 分隔符相同的函数。

我该如何解决这个问题?

最佳答案

你可以试试这个

def to_string(my_list, sep=', '):
    newstring = ''
    count = 0
    for string in my_list:
        if (length(my_list)-1) == count:
            newstring += str(string)
        else:
            newstring += str(string) + sep
        count += 1

return newstring  

然而,一个更简洁的方法是这样的:

sep = ', '
sep.join(map(str,my_list))

关于python - 如何将数字列表转换为字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44340491/

相关文章:

python - Ruby 相当于 Python chain()

python - 如何在 bazel `creation_time` 中设置 `lang_image`

python - logservice.fetch() 不返回任何内容

python - 使用变量调用 mongo 集合

python - 请求库 https 通过代理获取导致错误

python - python中的键盘输入数据类型

python - siamese-net 中的自定义组合铰链/kb-divergence 损失函数无法生成有意义的说话人嵌入

python - 变量如何在函数内部取值而不在任何地方声明

python - 为什么线程比子进程慢?我什么时候应该使用子进程代替线程,反之亦然

python - FastAPI 请求中的不可哈希类型