James Bellamy
James Bellamy

Reputation: 73

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

Upvotes: 0

Views: 55

Answers (2)

DM_Morpheus
DM_Morpheus

Reputation: 730

Iterating over lst would give you Game.Character objects in i in each iteration. Instead of i == x, use i.name == x

Upvotes: 0

Ernest S Kirubakaran
Ernest S Kirubakaran

Reputation: 1564

You should compare the input with the attribute of the instance.

for i in lst:
    if i.name == x:
        print("found")

Upvotes: 1

Related Questions