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

Python 如何将数字列表转换为字符串?,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: news

我要做的是获取给定的列表:
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_字符串测试
名单是:3,5,4,2,5,5
名单是:3-5-4-2-5-5

但是,我得到一个错误,上面写着
TypeError:不支持+:“int”和“str”的操作数类型

我认为这是因为其中一个打印语句是
print('List is:',List_函数.to_字符串(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))
另一种选择:

sep = ', '
output_str = sep.join([str(item) for item in my_list])

解决这个问题的另一种方法

L = [1,2,3,4,-5]
sep = ""
print(sep.join(list(map(str,L))))
希望这有帮助