如何使用openpyxl按值比较两个无序列并打印每行的结果?



我有一个包含两列的 excel 文件。列中的值是无序的。我确信源列中的某些单元格存在于目标列中,目标列更长(240 行与 191 行相比(。如何检查源列中的值是否存在于目标列中,然后逐行打印到目标列右侧的列,即"检查"源中的值是否存在,如果不存在,则"丢失"?

我认为它应该遵循这个逻辑,但值比较本身对我来说似乎很棘手:

for (source_row, target_row) in zip(ws.iter_rows(min_row=2, max_col=3, max_row=240),
ws.iter_rows(min_row=2, max_col=7, max_row=240)):
for (source_cell, target_cell) in zip(source_row, target_row):
if target_cell in source_row: # doesn't seem to work
ws.cell(column=10, row=target_cell.row).value = "check"
break
else:
ws.cell(column=10, row=target_cell.row).value = "missing"
break

对于这种事情,你应该避免使用嵌套循环。在这种情况下,它们不仅不一定有效,因为您只是检查单元格而不是针对一组值的单元格,嵌套循环可能会很快变慢,而且还会使调试和流量控制更加困难。

如果您只想知道每列中有哪些值。

source = set((r[0] for r in ws.iter_rows(min_row=2, max_row=240, min_col=3, max_col=3, values_only=True))
target = set((r[0] for r in ws.iter_rows(min_row=2, max_row=240, min_col=7, max_col=7, values_only=True))
missing_value = target - source
You can now loop over the source cells and do the comparison:
for row in ws.iter_rows(min_row=2, max_row=240, min_col=3, max_col=3):
for c in row:
value = c.value in target and "check" or "missing"
c.offset(rows=7).value = value

最新更新