gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:37:51 25 4
gpt4 key购买 nike

我有一个包含 int、float 和 string 的列表:

lists = [10, "test", 10.5]

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

val = ','.join(lists)
print val

我遇到这样的错误:

sequence item 0: expected string, int found

我该如何解决这个问题?

最佳答案

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

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

或者如果你想将列表中的每个元素都转换成字符串,那么试试-

>>> map(str,[10,"test",10.5])
>>> ['10', 'test', '10.5']

或者使用itertools提高内存效率(大数据)

>>>from itertools import imap
>>>[i for i in imap(str,[10,"test",10.5])]
>>>['10', 'test', '10.5']

或者简单地使用列表理解

>>>my_list=['10', 'test', 10.5]
>>>my_string_list=[str(i) for i in my_list]
>>>my_string_list
>>>['10', 'test', '10.5']

关于python - 使用python将列表转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33629703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com