【问题标题】:Python List output troubleshootingPython List 输出疑难解答
【发布时间】:2014-01-03 15:05:09
【问题描述】:

我有一个如下列表,并尝试将其写入 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

非常感谢您。

【问题讨论】:

    标签: python list tuples output


    【解决方案1】:
    1. 打开文件时使用with 自动清理文件句柄。
    2. 您仍然以方括号结尾,因为您要将列表转换为字符串。
    3. 您实际上并没有在任何地方使用标签

    我的建议是使用csv 模块,它还会为您处理转义(默认使用引号)。

    import csv
    
    final_out = [(['2893541', 'OVERALL', 'friendly and genuine.'], 77), (['2893382', 'SPEED', 'timely manner."'], 63)]
    
    with open('text.txt', 'wb') as fh:
        writer = csv.writer(fh, delimiter='\t')
    
        for row in final_out:
            writer.writerow(row[0] + [row[1]])
    

    【讨论】:

      【解决方案2】:

      你可以像这样修改写行:

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

      【讨论】:

        【解决方案3】:

        您可以尝试使用这种方法:

        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()
        

        【讨论】:

        • 请注意,鉴于工作的简单性,之前的代码没有使用任何其他附加库...
        猜你喜欢
        • 1970-01-01
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-09-06
        • 2014-08-29
        • 2011-10-27
        • 1970-01-01
        相关资源
        最近更新 更多