提问人:Devs 提问时间:10/4/2023 最后编辑:quamranaDevs 更新时间:10/4/2023 访问量:53
Python 比较 2 个列表并获取自定义输出
Python comparison of 2 list and get custom output
问:
我正在研究一个用例并坚持实施。
考虑一个列表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。totalAnimalCharList
totalAnimalCharList
AnimalType
totalAnimalCharList
['x','y','z','a']
id=1
答:
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]
评论
issubset()
type_X