问题描述:需要根据类别从一个对象数组中获取元素。
解决方法:可以使用循环遍历数组,根据指定的类别筛选出符合条件的元素。
以下是一个示例代码:
class Item:
def __init__(self, name, category):
self.name = name
self.category = category
# 定义一个对象数组
items = [
Item('item1', 'category1'),
Item('item2', 'category2'),
Item('item3', 'category1'),
Item('item4', 'category3'),
Item('item5', 'category2')
]
# 定义一个函数,根据类别从对象数组中获取元素
def get_items_by_category(items, category):
result = []
for item in items:
if item.category == category:
result.append(item)
return result
# 调用函数,获取指定类别的元素
category1_items = get_items_by_category(items, 'category1')
category2_items = get_items_by_category(items, 'category2')
# 打印结果
for item in category1_items:
print(item.name)
for item in category2_items:
print(item.name)
运行结果:
item1
item3
item2
item5
在这个示例中,我们定义了一个Item类,其中包含name和category两个属性。然后我们创建了一个对象数组items,并定义了一个函数get_items_by_category,该函数根据指定的类别从数组中筛选出元素。最后我们调用这个函数,获取指定类别的元素,并打印出结果。
这个方法可以根据不同的类别从对象数组中获取元素,具有一定的灵活性和可扩展性。