Skip to main content
 首页 » 编程设计

Python之打印列表中既没有逗号也没有撇号的项目

2025年05月04日14rubylouvre

我的代码的最小工作示例:

# Create output data file 
out_data_file = open('output_file','w') 
out_data_file.write("# Header \n") 
out_data_file.close() 
 
list1 = [1,3,4,5,12,6,2,35,74,6,2] 
 
# Open file to append 
with open('output_file', "a") as f: 
    f.write('Text'+'  '+str(['%d' % item for item in list1])) 

这给了我一个 output_file 看起来像:

# Header  
Text  ['1', '3', '4', '5', '12', '6', '2', '35', '74', '6', '2'] 

我希望输出看起来像这样:

# Header  
Text  1 3 4 5 12 6 2 35 74 6 2 

我该怎么做?

请您参考如下方法:

Use 
 
In [10]: list1 = [1,3,4,5,12,6,2,35,74,6,2] 
 
In [11]: " ".join(map(str, list1)) 
Out[11]: '1 3 4 5 12 6 2 35 74 6 2' 

...或者在您的情况下:

f.write('Text' + ' ' + " ".join(map(str, list1)))