【发布时间】:2014-09-05 07:24:46
【问题描述】:
我有一个脚本来读取 Excel 文件,其中单元格 A1 ~ A6 包含:
OK 17
OK 9
BKK 17
OK 16
OK 12
BKK 16
它们是 Excel 文件的唯一内容。
我要做的是检查单元格中的代码“OK”或“BKK”,并告诉我单元格中的代码是否与上面那一行相同。
例如,第 2 行有 'OK',这与第 1 行有 'OK' 相同,所以它会告诉我 'OK found' 和 'row no.2 and 1 found same code'。
但是下面运行的结果跳过了一些行:
from xlrd import open_workbook
the_file = open_workbook('c:\\file.xls',formatting_info=True)
the_sheet = the_file.sheet_by_index(0)
for row in range(0, the_sheet.nrows):
a = the_sheet.cell(row, 0).value
above_a = the_sheet.cell(row-1, 0).value
if a[0:2] == above_a[0:2]:
print 'row no.' + str(row + 1) + ' and ' + str(row) + ' found same code'
if 'OK' in a:
print 'OK found'
else:
print 'BKK found'
结果是:
row no.2 and 1 found same code
OK found
row no.5 and 4 found same code
OK found
逻辑错了。
澄清
有 6 个值要检查,所以我预计有 6 个结果,但只有 4 个。2 个被跳过。
可以这样算,但是有没有办法简化呢?
for row in range(0, the_sheet.nrows):
a = the_sheet.cell(row, 0).value
above_a = the_sheet.cell(row-1, 0).value
if a[0:2] == above_a[0:2] and 'OK' in a:
print 'row no.' + str(row + 1) + ' and ' + str(row) + ' found same code' + ' OK found'
if a[0:2] == above_a[0:2] and 'BKK' in a:
print 'row no.' + str(row + 1) + ' and ' + str(row) + ' found same code' + ' BKK found'
if a[0:2] != above_a[0:2] and 'BKK' in a:
print 'BKK found'
if a[0:2] != above_a[0:2] and 'OK' in a:
print 'OK found'
【问题讨论】:
-
代码根据您的描述打印正确的内容。什么不见了?如果 a 和 above_a 不相等,则不会打印任何内容。这就是你所说的跳过行的意思吗?另外,做 range(1,brows) 因为第一行永远不会匹配。
-
感谢 tdelaney。有 6 个值要通过,但结果只有 4 个。我的意思是缺少 2 个......
-
你的外部 if 需要一个带有打印语句的 else 子句。这将为每一行显示一些内容。
标签: python if-statement for-loop