Python 比较 2 个列表并获取自定义输出

问题描述 投票:0回答:1

我正在研究一个用例并坚持实施。

考虑列出一个清单

totalAnimalCharList = ['x','y','z','a','b','c']

考虑一个常量对象 AnimalType 如下 -:

class AnimalType():
    type_1 = {
        'id': 1,
        'animalCharList': ['x','y','z','a'],
    }
    type_2 = {
        'id': 2,
        'animalCharList': ['z'],
    }
    type_3 = {
        'id': 3,
        'animalCharList': ['c'],
    }

现在根据列表

totalAnimalCharList
我们需要找到它的id。例如,需要比较
totalAnimalCharList
和animalCharList(位于
AnimalType
类中),并且由于
totalAnimalCharList
具有type_1的每个元素,即
['x','y','z','a']
,我们需要返回
id=1
并重申与列出并返回所有匹配的 id。

python python-3.x list collections comparison
1个回答
0
投票

这是您原来问题的解决方案(但我还提供了一个简化的解决方案,没有

class
等 - 这实际上对初学者来说更容易):

totalAnimalCharList = ["x", "y", "z", "a", "b", "c"]


class AnimalType:
    type_1 = {
        "id": 1,
        "animalCharList": ["x", "y", "z", "a"],
    }
    type_2 = {
        "id": 2,
        "animalCharList": ["z"],
    }
    type_3 = {
        "id": 3,
        "animalCharList": ["c"],
    }


def get_type(lst):
    for k, v in vars(AnimalType).items():
        if k.startswith("type_") and set(v["animalCharList"]).issubset(lst):
            yield v["id"]


print(list(get_type(totalAnimalCharList)))

打印:

[1, 2, 3]

其他解决方案:仅使用带有字典的列表并将其中的列表转换为集合:

types = [
    {
        "id": 1,
        "animalCharList": {"x", "y", "z", "a"},
    },
    {
        "id": 2,
        "animalCharList": {"z"},
    },
    {
        "id": 3,
        "animalCharList": {"c"},
    },
]


def get_type(lst):
    for t in types:
        if t["animalCharList"].issubset(lst):
            yield t["id"]


print(list(get_type(totalAnimalCharList)))

打印:

[1, 2, 3]
© www.soinside.com 2019 - 2024. All rights reserved.