如何将数字列表转换为字符串?
问题描述:
我想要做的就是拿一个给定的名单: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 Test List is: 3, 5, 4, 2, 5, 5 List is: 3 - 5 - 4 - 2 - 5 - 5
但是,我得到一个错误,说
TypeError:不支持的操作数类型为+:'int'和'str'
我想这是因为打印语句之一是print('List is:', 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))
答
另一种选择:
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))))
希望这有助于