int元素转换成str
在Python中,有时需要将list以字符串的形式输出,此时可以使用如下的形式:
",".join(list_sample)
其中,,
表示的是分隔符
如需要将a_list = ["h","e","l","l","o"]
转换成字符输出,可以使用如下的形式转换:
a_list = ["h","e","l","l","o"] print ",".join(a_list)
如果list中不是字符串,而是数字,则不能使用如上的方法,会有如下的错误:
TypeError: sequence item 0: expected string, int found
可以有以下的两种方法:
#方法一 num_list = [0,1,2,3,4,5,6,7,8,9] num_list_new = [str(x) for x in num_list] print ",".join(num_list_new) #方法二 ai8py.com num_list = [0,1,2,3,4,5,6,7,8,9] num_list_new = map(lambda x:str(x), num_list) print ",".join(num_list_new)
string转换为int
假设有这样一个
results = [‘1’, ‘2’, ‘3’]
转化为下面这个样子
results = [1, 2, 3]
我们可以使用map函数
在Python2中这样操作:
results = map(int, results)
在Python3中这样操作:
results = list(map(int, results))