使用python将列表转换为字符串

Abd*_*zak 8 python list

我有它包含int,float和string的列表:

lists = [10, "test", 10.5]
Run Code Online (Sandbox Code Playgroud)

如何将上面的列表转换为字符串?我试过了:

val = ','.join(lists)
print val
Run Code Online (Sandbox Code Playgroud)

我收到这样的错误:

sequence item 0: expected string, int found
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

SIs*_*lam 12

首先str使用map函数将整数转换为字符串然后使用join函数 -

>>> ','.join(map(str,[10,"test",10.5]) )#since added comma inside the single quote output will be comma(,) separated
>>> '10,test,10.5'
Run Code Online (Sandbox Code Playgroud)

或者,如果您想将列表中的每个元素转换为字符串,请尝试 -

>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']
Run Code Online (Sandbox Code Playgroud)

itertools用于内存效率(大数据)

>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']
Run Code Online (Sandbox Code Playgroud)

或者只是使用列表理解

>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']
Run Code Online (Sandbox Code Playgroud)


Tig*_*kT3 5

最简单的方法是将整个内容发送到str()or repr()

>>> lists = [10, "test", 10.5]
>>> str(lists)
"[10, 'test', 10.5]"
Run Code Online (Sandbox Code Playgroud)

repr()可能会产生不同的结果,str()具体取决于list. 关键repr()是您可以将此类字符串发送回eval()ast.literal_eval()取回原始对象:

>>> import ast
>>> lists = [10, "test", 10.5]
>>> ast.literal_eval(repr(lists))
[10, 'test', 10.5]
Run Code Online (Sandbox Code Playgroud)