[英]Python Find object in a list of objects
我有一个对象列表,我想找到一个特定的 object。
我有一个文本文件,其中包含有关宠物饥饿程度和位置的数据:
The cat,5,at the door
The dog,1,at the bed
The bunny,4,at the car
我的代码如下所示:
class Pets:
def __init__(self, pet, hunger, where):
self.pet=pet
self.hunger=hunger
self.where=where
def main():
data=readFile()
allPets=makeObjects(data)
howHungry(allPets)
def readFile():
with open('data.txt') as cvsfile:
reader = csv.reader(cvsfile)
i=0
data = []
for row in reader:
i+=1
print(row)
data.append(row)
return (data)
def makeObjects(data):
allPets=[]
i=0
while i < len(data):
allPets.append(Pets(data[i][0], data[i][1], data[i][2]))
i += 1
return allPets
def howHungry(allPets):
一切正常,直到我到达 howHungry function。我想打印狗有多饿。 我如何找到狗在对象列表中的位置? 我曾尝试使用索引,但这只适用于列表。
由于您有一个包含Pets
object 个实例的列表,因此您确实不能直接使用.index()
; 相反,您需要某种循环; 这里只是一个普通的旧for
循环。
def print_hungry_doggos(all_pets):
for pet in all_pets: # loop over all pets
if "dog" in pet.pet: # if the name contains dog, assume it's a dog
print(f"{pet.pet}'s hunger level is {pet.hunger}")
作为旁白:
snake_case
,而不是camelCase
,在 Python 中。while
循环在 Python 中通常很少见。您的代码更惯用(不使用例如列表理解)作为
import csv
class Pet:
def __init__(self, pet, hunger, where):
self.pet = pet
self.hunger = hunger
self.where = where
def __str__(self):
return f"{self.pet} is {self.hunger} in {self.where}"
def read_file():
with open('data.txt') as cvsfile:
return list(csv.reader(cvsfile)) # iterates over the CSV reader to generate a single list of lists
def make_objects(csv_data):
pets = []
for row in csv_data:
pets.append(Pet(pet=row[0], hunger=row[1], where=row[2]))
return pets
def main():
csv_data = read_file()
all_pets = make_objects(csv_data)
for pet in all_pets:
print(pet)
您可以通过覆盖eq dunder function 来执行此操作。这是一个示例:
class Animal:
def __init__(self, animal, hunger, location):
self.animal = animal
self.hunger = hunger
self.location = location
def __eq__(self, other):
if isinstance(other, str):
return other == self.animal
if isinstance(other, Animal):
other.animal == self.animal
return False
animal_1 = Animal('dog', 5, 'In the garden')
animal_2 = Animal('cat', 2, 'In the bedroom')
lst = [animal_1, animal_2]
for animal in ['dog', 'cat', 'monkey']:
try:
i = lst.index(animal)
print(f'The {animal} is {lst[i].location}')
except ValueError:
print(f'Couldn\'t find the {animal}')
Output:
The dog is In the garden
The cat is In the bedroom
Couldn't find the monkey
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.