我想做的是获取一个给定的列表:
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/