-1

I have a list of objects. I would like to check some string if that string exists as a field value any object in the list. for example,

class Ani:
    name = ''
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name


animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')

a = [animal1, animal2, animal3,animal4,animal5]

my problem to write a code in order to see if there is an object with given name. for example "chip".

Odiljon Djamalov
  • 761
  • 8
  • 11
  • Questions asking for homework help must include a summary of the work you've done so far to solve the problem, and a description of the difficulty you are having solving it. **There is no attempt to solve your task.** Please read [How to ask homework questions](//meta.stackoverflow.com/q/334822) and [edit] your post. – Patrick Artner Apr 29 '19 at 07:33
  • Duplicate: [find-object-in-list-that-has-attribute-equal-to-some-value-that-meets-any-condition](https://stackoverflow.com/questions/7125467/find-object-in-list-that-has-attribute-equal-to-some-value-that-meets-any-condi) – Patrick Artner Apr 29 '19 at 07:41

4 Answers4

4

You can iterate over the array of objects, and check with each object's getName function.

class Ani:
    name = ''
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name


animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')

animals = [animal1, animal2, animal3,animal4,animal5]

searched_animal = 'rex'

for animal in animals:
  if animal.getName() == searched_animal:
    print('Found')
    break
Shuvojit
  • 1,390
  • 8
  • 16
4

You can use any plus a comprehension:

any(animal.getName() == "chip" for animal in animals)
Netwave
  • 40,134
  • 6
  • 50
  • 93
0

You can use the getName method present in Ani class for this program

class Ani:
    name = ''
    def __init__(self, name):
        self.name = name

    def getName(self):
        return self.name


animal1 = Ani('alica')
animal2 = Ani('rex')
animal3 = Ani('bobik')
animal4 = Ani('dobik')
animal5 = Ani('sobik')

animals = [animal1, animal2, animal3,animal4,animal5]

key = 'chip'

flag=0
for animal in animals:
    if animal.getName() == key:
        print('Found')
        flag=1
        break

if flag==0:
    print("Not Found")
Karthik Vg
  • 108
  • 13
0

Iterating a list containing anything is quite simple really. Like so:

animal_to_find = "someAnimal"
for animal in animals:
  if animal.getName() == animal_to_find:
    print("Found a match for: " + animal)  
Skydt
  • 1
  • 1