I am working on a use case and stuck with implementation.
Consider a list totalAnimalCharList = ['x','y','z','a','b','c']
Consider a constant object AnimalType as below -:
class AnimalType():
type_1 = {
'id': 1,
'animalCharList': ['x','y','z','a'],
}
type_2 = {
'id': 2,
'animalCharList': ['z'],
}
type_3 = {
'id': 3,
'animalCharList': ['c'],
}
Now based on the list totalAnimalCharList
we need to find it's id. For example need to compare totalAnimalCharList
and animalCharList( which is in AnimalType
class) and since totalAnimalCharList
has every element of type_1 i.e. ['x','y','z','a']
, we need to return id=1
and reiterate to compare with other ids in the list and return all matched ids.
Here is solution to your original problem (but I also offer a simplified solution without class
etc. - that is actually easier for beginner):
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)))
Prints:
[1, 2, 3]
Other solution: Use just list with dictionaries and convert the lists there to sets:
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)))
Prints:
[1, 2, 3]