[英]Finding objects in a list by an attribute
我有以下代码。 我正在尝试创建对象列表,然后让用户输入他们想查找的对象的名称或属性,以便他们可以在清单中找到该对象。 谢谢
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()
您应该将输入与实例的属性进行比较。
for i in lst:
if i.name == x:
print("found")
迭代lst
将在每次迭代中为您Game.Character
i
中的Game.Character
对象。 代替i == x
,使用i.name == x
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.