Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python列表输出故障排除_Python_List_Tuples_Output - Fatal编程技术网

Python列表输出故障排除

Python列表输出故障排除,python,list,tuples,output,Python,List,Tuples,Output,我有一个列表,如下所示,并试图将其写入一个以制表符分隔的txt文件 final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)] 我的输出语句是,但它并没有消除方括号: fh = open("text.txt", "w") fh.write('\n'.join('%s %s' % x for x in final_out)) f

我有一个列表,如下所示,并试图将其写入一个以制表符分隔的txt文件

final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]
我的输出语句是,但它并没有消除方括号:

fh = open("text.txt", "w")
fh.write('\n'.join('%s %s' % x for x in final_out))
fh.close()
我期望的输出是:

2893541 OVERALL friendly and genuine.   77 
2893382 SPEED   timely manner.  63
事先非常感谢你

  • 打开文件时使用可自动清理文件句柄
  • 因为要将列表转换为字符串,所以最终还是会出现方括号
  • 实际上,您并没有在任何地方使用选项卡
  • 我的建议是使用
    csv
    模块,该模块还将为您处理转义(默认情况下使用引号)


    可以按如下方式修改写入行:

    fh.write('\n'.join('%s %s' % (' '.join(a), b) for a, b in final_out))
    

    您可以尝试使用以下方法:

    final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]
    fh = open("text.txt", "w")
    
    for final_out_item in final_out:
        first_part = '\t'.join(final_out_item[0])
        fh.write("%s\t%s\n" % (first_part, final_out_item[1]))
    
    fh.close()
    

    请注意,鉴于所做工作的简单性,前面的代码没有使用任何其他库。。。
    final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]
    fh = open("text.txt", "w")
    
    for final_out_item in final_out:
        first_part = '\t'.join(final_out_item[0])
        fh.write("%s\t%s\n" % (first_part, final_out_item[1]))
    
    fh.close()