我有这样的剧本;
for b in range(len(xy_alignments.keys())):
print str(b) + " : " + str(len(xy_alignments.keys()))
x = xy_alignments.keys()[b][0]
y = xy_alignments.keys()[b][1]
yx_prob = yx_alignments[(y,x)] / x_phrases[x]
xy_prob = xy_alignments[(x,y)] / y_phrases[y]
line_str = x + "\t" + y + "\t" + str(yx_prob) + "\t" + str(xy_prob) + "\n"
of.write(line_str.encode("utf-8"))
of.close()
xy_alignments
,yx_alignments
,x_phrases
和y_phrases
是
python defaultdict 涉及数百万个密钥的变量。
当我在上面运行循环时,它会慢慢地运行。
蟒蛇爱好者有建议加快速度吗?
谢谢,
答案 0 :(得分:2)
这是一个更惯用的版本,也应该更快。
for (x, y), xy_alignment in xy_alignments.iteritems():
yx_prob = yx_alignments[(y, x)] / x_phrases[x]
xy_prob = xy_alignment / y_phrases[y]
of.write(b'%s\t%s\t%s\t%s\n' % (x, y, yx_prob, xy_prob))
此
key()
来电,iteritems()
,encode()
调用,因为无论如何所有输出都在ascii范围内。