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

Python comparison of 2 list and get custom output

提问人:Devs 提问时间:10/4/2023 最后编辑:quamranaDevs 更新时间:10/4/2023 访问量:53

问:

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

考虑一个列表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'],
    }

现在,根据列表,我们需要找到它的 id。例如,需要比较和 animalCharList( 在类中),并且由于具有 type_1 的每个元素,即 ,我们需要返回并重申以与列表中的其他 id 进行比较并返回所有匹配的 id。totalAnimalCharListtotalAnimalCharListAnimalTypetotalAnimalCharList['x','y','z','a']id=1

python-3.x 列表 集合 比较

评论

2赞 quamrana 10/4/2023
请使用您尝试过的代码更新您的问题。
0赞 Devs 10/4/2023
@quamrana 对不起,我是 Python 的新手,甚至不知道如何尝试这种列表比较。
0赞 quamrana 10/4/2023
那么,这个问题是从哪里来的,你有什么策略来解决这个问题?
0赞 Barmar 10/4/2023
将列表转换为集合,并使用其方法。issubset()
0赞 Barmar 10/4/2023
不要使用单独的变量。将所有词典放在一个列表中,以便您可以循环访问它。type_X

答:

1赞 Andrej Kesely 10/4/2023 #1

这是您原始问题的解决方案(但我也提供了一个简化的解决方案,没有等 - 这实际上对初学者来说更容易):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]