简体   繁体   English

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

[英]How to convert a list of numbers into a string?

What I'm trying to do is take a given list: 我要做的是拿一个给定的列表:
numlist_1: [3, 5, 4, 2, 5, 5]
and convert it to a string using this function 并使用此函数将其转换为字符串

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  

With the desired output to appear as: 所需的输出显示为:
to_string Test List is: 3, 5, 4, 2, 5, 5 List is: 3 - 5 - 4 - 2 - 5 - 5

However, I get an error which says 但是,我收到一个错误
TypeError: unsupported operand type(s) for +: 'int' and 'str' TypeError:+:'int'和'str'的不支持的操作数类型

I think this is because one of the print statements is 我认为这是因为其中一个印刷声明是
print('List is:', list_function.to_string(num_list1, sep=' - '))
and the separator is different from the one given in the function but I want to be able to accompany for both ', ' and ' - ' seperators as I have another list which uses the same function with the ', ' seperator instead. 并且分隔符与函数中给出的分隔符​​不同,但我希望能够同时包含','和' - '分隔符,因为我有另一个列表,它使用与','分隔符相同的函数。

How do I get around this? 我该如何解决这个问题?

You can try this 你可以试试这个

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  

However, a much concise way is this: 但是,这是一个非常简洁的方法:

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

Another option: 另外一个选项:

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

another way to solve this problem 另一种解决这个问题的方法

L = [1,2,3,4,-5]
sep = ""
print(sep.join(list(map(str,L))))

hope this helps 希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM