在我的代码中,我有一个项目列表:
animals = ['LION', 'TIGER', 'DEER', 'CHICKEN']
和一个空列表:
new_catch = []
其余代码:
farm =[
{'LION':'carnivorous', 'legs': 4 , 'strength': 98.7, 'kills': True},
{'TIGER':'carnivorous', 'legs': 4 , 'strength': 100.18, 'kills': True},
{'DEER':'harbivorous', 'legs': 4, 'speed': 87.3, 'kills': False},
{'CHICKEN':'null', 'legs': 2, 'speed': 5, 'strength':2.3, 'kills': False},
{'PIG': 'omnivorous', 'legs': 4, 'strength': 55.0, 'kills': True, 'speed':64}
]
while not(new_catch in animals):
animal = input("give me a:... ").upper()
for animals in farm:
for key, value in animals.items():
if animal in animals:
print('')
print("#{}:{}".format(key, value))
print('')
else:
new_catch.append(animal)
print("sorry, {} is not available!!".format(new_catch))
print(new_catch)
我想要列出名单中的动物名称(动物),但我想比较这些名字,这样如果我叫出名单不在我的名单中(动物),它会被添加到我的名单中空列表(new_catch)。我不确定如何表达它("如果不是"),但它给了我错误。
答案 0 :(得分:0)
首先,我认为您所看到的错误的问题在于您已宣布"动物"这里两次,一次作为列表,一次作为while循环中的索引。它会认为你试图在列表中哈希。尝试给第二个声明一个唯一的名称。
其次,您是否实际使用new_catch列表执行任何操作,或者只是在适用的位置添加新输入。如果是这样,你需要使while更加通用,以确保输入/输出的持续循环,但在输入调用之后还将所有条件移动到。
while True:
animal = input("give me a:... ").upper()
for farmAnimals in farm:
for key, value in farmAnimals.items():
if animal in farmAnimals:
print('')
print("#{}:{}".format(key, value))
print('')
else:
if not (animal in new_catch):
new_catch.append(animal)
print("sorry, {} is not available!!".format(animal))
print(animal)
答案 1 :(得分:0)
如果我理解正确,你会尝试做类似的事情
while new_catch != farm:
name = input("give me a:... ").upper()
found = False
for animals in farm:
if name in animals: # Check if that animal name exists as a key
found = True
print(name) # print name as a header
for key, value in animals.items():
if key!=name: # print everything but the name
print("#{}:{}".format(key, value))
new_catch.append(animal) # add the entered animal
break # end the farm loop since we added an animal
# print that we can't find the input, and repeat the while loop
if not found:
print("sorry, we do not have a {} yet!".format(animal))
new_catch.append(animal) #add the input list
print("Caught so far: {}".format(new_catch))