[英]Finding objects in a list by an attribute
I have the following code. 我有以下代码。 I am trying to create a list of objects, then have user input the name or an attribute of the object they would like to find, so they can find that object in their inventory.
我正在尝试创建对象列表,然后让用户输入他们想查找的对象的名称或属性,以便他们可以在清单中找到该对象。 Thanks
谢谢
import Game
import sys
import os
import time
import random
if __name__ == '__main__':
pass
#constructor = name, ability, hitpoints, attack, gold, potions
def main():
lst=[]
c1 = Game.Character('j', "Forcefield", 100, 10, 0, 0)
lst.append(c1)
c2 = Game.Character("Sue", "Jump", 100, 10, 0, 0)
lst.append(c2)
x = input("Enter the name of the character to search for")
for i in lst:
if i == x:
print("found")
main()
You should compare the input with the attribute of the instance. 您应该将输入与实例的属性进行比较。
for i in lst:
if i.name == x:
print("found")
Iterating over lst
would give you Game.Character
objects in i
in each iteration. 迭代
lst
将在每次迭代中为您Game.Character
i
中的Game.Character
对象。 Instead of i == x
, use i.name == x
代替
i == x
,使用i.name == x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.