我想在列表中的元素之间添加一个换行符(python)

我想在列表中的元素之间添加一个换行符(python),python,Python,此函数用于创建混淆矩阵并将其写入新文件 看起来像 这是一个没有空格的嵌套列表,但我想让它看起来像: 通过在元素之间添加新行 我尝试过添加 def writeConfusionMatrix(self, outFile): print("Write a confusion matrix to outFile; elements in the matrix can be frequencies (you don't need to normalize)") output = []

此函数用于创建混淆矩阵并将其写入新文件

看起来像

这是一个没有空格的嵌套列表,但我想让它看起来像:

通过在元素之间添加新行

我尝试过添加

def writeConfusionMatrix(self, outFile):
    print("Write a confusion matrix to outFile; elements in the matrix can be frequencies (you don't need to normalize)")

    output = []

    file = open(outFile, 'w+')

    matrix = defaultdict(lambda: defaultdict(int))

    for s in range(len(self.goldenTags)):
        for w in range(len(self.goldenTags[s])):
            matrix[self.goldenTags[s][w].tag][self.myTags[s][w].tag] += 1

    row_ids = sorted(matrix.keys())
    col_ids = sorted(set(k for v in matrix.values() for k in v.keys()))

    output.append(col_ids)

    for r in row_ids:
        output.append([r] + [matrix[r].get(c, 0) for c in col_ids])
    #matKeys = matrix.keys()
    #df = DataFrame(matrix).T.fillna(0)
    #output = '\n'.join(output)
    print(output)
    file.write(str(output))
以前

output = '\n'.join(output)
但是给了我一个

file.write(str(output))
错误


有什么想法吗?

试着将此内容写入您的文件:

sequence item 0: expected str instance, list found

您正在使用
'\n.join()
连接列表,您还需要将这些列表转换为字符串。

只需逐行打印字符串:

output = '\n'.join([','.join(map(str,item)) for item in output])
或者创建一个使用新行分隔符的新字符串,然后将其写入:

for line in output:
    print line # or file.write(line)

file.write('\n.join(str(item)表示lst中的item))
我应该把这个放在file.write之前吗?它给了我一个错误:序列项1:预期的str实例,int found
output = '\n'.join(str(line) for line in output)
print line # or file.write(line)