python - 检查数组Python列表中的元素
问题描述
我想检查数组列表中是否有一个元素,例如,我有:
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
因此,如果我想检查“马 A”是否在列表中。我试过了:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check,treatment))
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
但是如果我输入的马名是:“horse B”。输入还将检查列表中的每个数组并打印出数组 1 中未找到的语句。
input:
Enter the horse name:horse B
horse B id 2 profile is not in the database. (You must enter the horse's profile before adding med records)
Enter treatment:
那么我怎样才能摆脱它呢?谢谢你。
解决方案
你只需要移动else
to 成为 for 循环的一部分:
horsename_check = input("Enter horse name: ")
for i in horselist:
if (i[1] == horsename_check):
treatment = input("Enter treatment: ")
print("{0} found with treatment {1}".format(horsename_check, treatment))
break
else:
print("{0} id {1} profile is not in the database. "
"(You must enter the horse's profile before adding med records)".format(horsename_check, i[0]))
推荐阅读
- python - GeoDjango如何在此查询中以米为单位显示距离
- angular - Angular 12 升级后 Karma 没有运行单元测试
- google-apps-script - 如何将 FOR LOOP 添加到此 Google 脚本代码中?
- java - 机器人竞赛 -> 机器人在笛卡尔网格上移动。L 是左 90 度,R 是右 90 度,F 是向前一格。请看附件截图
- r - 如何使用ggtext将图像绘制为y轴标签?
- java - 创建比可用处理器更多的线程会产生性能开销吗?
- javascript - 查询 INSERT - 引用和反斜杠
- python - 列表列表的内存问题
- javascript - 将原始 CSS 转换为 Javascript DOM 样式属性
- excel - 如何从 Excel 中获取无序集中的下一个最大值