检查数组列表中的元素

  • 本文关键字:元素 列表 数组 python
  • 更新时间 :
  • 英文 :


我想检查数组列表中是否有元素例如,我有:

horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]

如果我想检查是否&;horse &;在列表中。我试着:

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]))

但是如果我输入马的名字是:"马"Input还将检查列表中的每个数组,并打印出在数组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移动到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]))

您需要打印"未找到的马";消息仅在之后遍历整个列表,而不是每次都找到元素。你应该在找到正确的马后退出循环,在那个点之外迭代没有意义。您应该使用forelse结构:

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]))
horselist = [(1,"horse A","owner of A"), (2,"horse B", "owner of B")]
neededHorse = "horse B"
found = 0
for horse in horselist:
if neededHorse in horse:
found = horse[0]
if found != 0:
print("Horse found in ",found)
else:
print("Horse not found!")

这应该可以,你可以在循环外保留一个条件,并在循环后检查

最新更新