在Python中迭代对象时使用标志的替代方法

我有一个使用xlrd比较两个.xls表单之间的值的脚本。 默认情况下,它让我寻找相似之处,并将它们写入一个txt文件。 如果我通过一个参数,我可以查找每个.xls唯一的设备,并将其写入到txt文件。 现在,我遍历每个.xls中的行,并在两个文件之间find相似性时将其标记为True。 当标志被标记为False时,它只会从第一张表中写入主机。 这是一些带有标志的代码:

else: for row1 in range(sheet1.nrows): inboth = False for row2 in range(sheet2.nrows): if sheet2.row_values(row2)[0].split(".")[0] == sheet1.row_values(row1)[0].split(".")[0]: inboth = True if not inboth: outfile.write(sheet1.row_values(row1)[0].split(".")[0] + ",File1\n") for row2 in range(sheet2.nrows): inboth = False for row1 in range(sheet1.nrows): if sheet1.row_values(row1)[0].split(".")[0] == sheet2.row_values(row2)[0].split(".")[0]: inboth = True if not inboth: outfile.write(sheet2.row_values(row2)[0].split(".")[0] + ",File2\n") 

有没有更有效的方式来做到这一点,而不使用“inboth”标志? 有没有解决scheme,我不需要两次遍历两张表?

你想要的是Python set数据types。 http://docs.python.org/library/sets.html遍历第一个文件,把你在集合sfind的所有设备,然后把第二个filw中的所有设备放在集合t 。 然后做:

r = s.symmetric_difference(t)

r将有一个设备列表,但不是两个文件。