0

I have made a classifier in Python and it works fine. Now I need to output the results into a text file, which I can also do without a problem. The problem is, I need to include the id of the result as well as the result itself. I am new to python and still getting used to the syntax so any help would be greatly appreciated.

    printedRow = '{id1},{result1}'.format(id1=id , result1 = result)
    print("~~~~~RESULT~~~~~")

    for k in range(0,len(pans)):
         pans.append(row[0] + ','+ p.classify(row))

    print (pans)
    print(pans, file=outfile)

The id that I need to include with the results of the classifier is being held in the index row[0]. When I run this code, the same id is printed with every result. The results are printing out fine, I just need to be able to match the id with the result.

They are both held in lists and there are about 2000 values in each list.

4

1 回答 1

0

我不确定您要做什么,因为您没有定义什么row或是什么pans。考虑使用更多 Pythonic 源代码。如果对象是任何类型的集合,则使用某种迭代器。枚举对于给每个循环一个索引号很有用。

for n, p in enumerate(pans):
    print "pan %d is %s" % (n, p)

您似乎还附加到pans一个大小取决于pans. 那可以永远持续下去!

如果要添加到列表中,只需添加它,例如:

newpans = pans + [x.classify(row) for x in oldpans]

与其在内存中建立结构,然后将其打印到文件中,不如直接写入文件。这将占用更少的内存。如果你想要速度,让计算机为你缓冲文件,例如

f = open("output.txt", "w")
for n, p in enumerate(pans):
    f.write("%s,%s\n" % (n, classify(p)))
f.close()
于 2012-04-29T15:14:25.987 回答