我正在研究一个用例并坚持实施。
考虑列出一个清单
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。
这是您原来问题的解决方案(但我还提供了一个简化的解决方案,没有
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]