python - 如何在使用 .iter_rows 时获取“当前”行值?
问题描述
我正在为我的研究小组开发访问控制系统,并且在使用我的数据库对用户进行身份验证时遇到了困难。我需要遍历一定数量的行(在 .xlsx 文件中)并检查我的值是否与列上的任何值匹配。如果是,则将授予访问权限。否则,我需要打印一条错误消息。我想知道是否有任何更聪明的方法来完成这项工作,因为就我检查 openpyxl 文档而言,它没有说任何有助于在迭代行时提取当前行的值的内容。
目前我有一种硬编码的方式来使它工作,使用一个辅助变量(n),它在迭代的每一行上递增。每次迭代,'n' 被测试等于工作表上的行数。如果它相等,则意味着循环已到达表的末尾并且未找到用户。
# Checks if the UID was succesfully stored and is accessible
for row in ws.iter_rows():
if row[5].value == user.pin:
print('Cadastro realizado com sucesso!')
wb.close()
del user
break
if n == ws.max_row:
print('Usuário não autorizado')
wb.close()
gpio.output(10, gpio.LOW)
del user
n = 0
n = n + 1
我一直在寻找一些替代方案,row.row
或者row.value
在迭代时返回我当前所在的行。
解决方案
由于返回一个可迭代对象,因此您可以在遍历工作表ws.iter_rows()
时使用 Python 的内置函数来获取索引。enumerate
它几乎就像您当前的幕后解决方案一样工作,但使代码更清晰,更具可读性。
您的代码如下所示:
# Checks if the UID was succesfully stored and is accessible
for idx, row in enumerate(ws.iter_rows()):
if row[5].value == user.pin:
print('Cadastro realizado com sucesso!')
wb.close()
del user
break
if idx + 1 == ws.max_row:
print('Usuário não autorizado')
wb.close()
gpio.output(10, gpio.LOW)
del user
推荐阅读
- reactjs - SetState 没有改变状态值
- r - 在一个数据集中查找与 R 中另一个数据集中的坐标缓冲区匹配的坐标
- python - 在 Python 中使用 .CSV 中的列附加空列表
- machine-learning - 如何在 SimpleImputer 中选择策略
- reactjs - React 无法从返回中访问变量
- git - 如何从私有远程存储库中删除旧的 git 条目?
- django - 如何使 django 上传的图像显示在 CloudFront 前端 + Beanstalk 后端
- api - 亚马逊产品广告 API - 检查购物车中的商品是否实际购买?
- git - 创建基于 ssh 的远程路径
- mule-studio - Mule Munit 模拟和间谍功能