You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Regex搜索类对象列表,实现动物园老虎筛选功能?

如何用正则表达式筛选动物园中的老虎对象

我有一项作业要求:添加一个方法,使用Regex从动物园中筛选出老虎并查看它们,提示需要遍历动物园内的所有动物。我不清楚如何使用Regex搜索类对象名称列表,希望能得到相关提示!以下是我的Python代码:

import functools
import re


class Animal:
    def __init__(self):
        self.__numberOfLegs = 4
        self.__numberOfHands = 0

    def look(self):
        return "\nNumber of hands: {hand}, Number of legs: {leg}".format(
            hand=self.__numberOfHands, leg=self.__numberOfLegs)


class Bird:
    def __init__(self):
        self.__numberOfLegs = 2
        self.__numberOfWings = 2

    def look(self):
        return "\nNumber of wings: {wing}, Number of legs: {leg}".format(
            wing=self.__numberOfWings, leg=self.__numberOfLegs)


class Feline(Animal):
    def __init__(self):
        Animal.__init__(self)
        self.__characteristic = "Felines belong to the cat family"

    def look(self):
        return super().look() + "\n" + self.get_characteristic()

    def get_characteristic(self):
        return self.__characteristic


class Tiger(Feline):
    def __init__(self):
        Feline.__init__(self)
        self.__characteristic = "Tigers can roar and are lethal predators\n"

    def get_characteristic(self):
        return super().get_characteristic() + "\n" + self.__characteristic


class WildCat(Feline):
    def __init__(self):
        Feline.__init__(self)
        self.__characteristic = "Wild cats can climb trees\n"

    def get_characteristic(self):
        return super().get_characteristic() + "\n" + self.__characteristic


class Canine(Animal):
    def __init__(self):
        Animal.__init__(self)
        self.__characteristic = "Canines belong to the dog family"

    def look(self):
        return super().look() + "\n" + self.get_characteristic()

    def get_characteristic(self):
        return self.__characteristic


class Wolf(Canine):
    def __init__(self):
        Canine.__init__(self)
        self.__characteristic = "Wolves hunt in packs and have a leader\n"

    def get_characteristic(self):
        return super().get_characteristic() + "\n" + self.__characteristic


class FlightBird(Bird):
    def __init__(self):
        Bird.__init__(self)
        self.__characteristic = "Flight birds fly and hunt for food"

    def look(self):
        return super().look() + "\n" + self.get_characteristic()

    def get_characteristic(self):
        return self.__characteristic


class Eagle(FlightBird):
    def __init__(self):
        FlightBird.__init__(self)
        self.__characteristic = "Eagles fly extremely high and can see their prey from high up in the sky\n"

    def get_characteristic(self):
        return super().get_characteristic() + "\n" + self.__characteristic


class Zoo:
    def __init__(self):
        self.__animalList = list()
        self.__birdList = list()

    def add(self, living_thing):
        if not isinstance(living_thing, Animal) and not isinstance(living_thing, Bird):
            raise Exception("Only animals and birds can be passed")
        try:
            if isinstance(living_thing, Animal):
                if len(list(filter(lambda a: type(a) == type(living_thing), self.__animalList))) == 0:
                    if len(self.__animalList) < 2:
                        self.__animalList.append(living_thing)
                        print("Animal Added")
                    else:
                        print("Zoo full for animals")
                else:
                    print("Creature already in zoo")
            elif isinstance(living_thing, Bird):
                if len(self.__birdList) < 1:
                    self.__birdList.append(living_thing)
                    print("Bird Added")
                else:
                    print("Zoo full for birds")
        except Exception:
            print("An error has occurred")
        else:
            print("Completed without errors\n")

    def looking(self):
        print(Zoo.__look_all_contents(self.__animalList + self.__birdList))

    def find_canine(self):
        canine_in_zoo = map(lambda h: h.look(), list(filter(lambda g: isinstance(g, Canine), self.__animalList)))
        print(*canine_in_zoo)

    def find_tiger(self):
        # 待实现
        pass

    @staticmethod
    def __look_all_contents(combined_lists):
        if len(list(combined_lists)) == 0:
            return "Zoo is empty"
        string_reduce_map = functools.reduce(lambda x, y: x + y, map(lambda j: j.look(), list(combined_lists)))
        return string_reduce_map


zoo = Zoo()
zoo.add(Tiger())
zoo.add(Wolf())
zoo.add(Eagle())
zoo.looking()
zoo.find_canine()
zoo.find_tiger()

解决方案

要通过正则筛选类对象,核心是先获取对象的类名字符串,再用正则匹配该字符串。Python中可以通过type(obj).__name__获取对象所属类的名称,之后就能用re模块进行匹配。

实现find_tiger方法

替换Zoo类中空的find_tiger方法为以下代码:

def find_tiger(self):
    # 编译正则表达式,精确匹配类名"Tiger"
    tiger_regex = re.compile(r'^Tiger$')
    # 合并动物园中的动物和鸟类列表
    all_creatures = self.__animalList + self.__birdList
    # 遍历所有生物,筛选类名匹配正则的对象
    tigers = []
    for creature in all_creatures:
        class_name = type(creature).__name__
        if tiger_regex.match(class_name):
            tigers.append(creature)
    # 输出老虎的信息
    if tigers:
        for tiger in tigers:
            print(tiger.look())
    else:
        print("动物园里没有老虎。")

补充说明

  • 如果需要更灵活的匹配规则(比如不区分大小写匹配"tiger"),可以修改正则表达式并添加忽略大小写参数:
    tiger_regex = re.compile(r'tiger', re.IGNORECASE)
    
  • 实际开发中,用isinstance(creature, Tiger)筛选对象更直接高效,但因为作业要求必须使用正则,所以采用上述方式。

内容的提问来源于stack exchange,提问作者DWAlta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:25:22