Python 3.x Python:将数字列表转换为字符串列表
我在此表格中有一份编号列表:Python 3.x Python:将数字列表转换为字符串列表,python-3.x,list,Python 3.x,List,我在此表格中有一份编号列表: [[2, 3, 4], [0, 2, 3, 4], [1, 3, 4], [1, 2, 4], [2]] 我希望将此列表转换为: ['2 3 4', '0 2 3 4', '1 3 4', '1 2 4', '2'] 我该怎么做呢?你可以像这样使用列表理解 my_list=[[2,3,4]、[0,2,3,4]、[1,3,4]、[1,2,4]、[2]] 格式化=[“”。在我的_列表中为x加入(映射(str,x))] 打印(格式化) 印刷品 ['2
[[2, 3, 4], [0, 2, 3, 4], [1, 3, 4], [1, 2, 4], [2]]
我希望将此列表转换为:
['2 3 4', '0 2 3 4', '1 3 4', '1 2 4', '2']
我该怎么做呢?你可以像这样使用列表理解
my_list=[[2,3,4]、[0,2,3,4]、[1,3,4]、[1,2,4]、[2]]
格式化=[“”。在我的_列表中为x加入(映射(str,x))]
打印(格式化)
印刷品
['2 3 4', '0 2 3 4', '1 3 4', '1 2 4', '2']
您需要迭代列表中的所有子列表,然后将子列表加入字符串并将其附加到新列表中。代码如下所示:
list = [[2, 3, 4], [0, 2, 3, 4], [1, 3, 4], [1, 2, 4], [2]]
result = []
for sublist in list:
result.append(" ".join(map(str, sublist))) # join accepts only string lists, so you need to convert the sublist into the list of integer which is achieved via map function
现在打印(结果)
将输出:
['2 3 4', '0 2 3 4', '1 3 4', '1 2 4', '2']
你的代码在哪里,有什么问题?问题可能是重复的。在2分钟内找到了副本