首页 > 解决方案 > 检查数组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: 

那么我怎样才能摆脱它呢?谢谢你。

标签: python

解决方案


你只需要移动elseto 成为 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]))

推荐阅读