def entity_mappings(mapping, entities_list):
entity_mapped = []
for (key, value) in mapping.items():
for i in entities_list:
if i == key:
entity_mapped.append(value)
return entity_mapped
我想从id的实体列表中匹配密钥,并将密钥的值附加到实体映射列表中,然后返回,是否有更好的方法来执行此任务?映射是字典。
答案 0 :(得分:2)
您可以使用list comprehension
这样
方法1
entity_mapped = [value for (key, value) in mapping.items() if key in entities_list]
您可以在entities_list
内进行搜索,而无需进行迭代和匹配。
复杂度:O(nm)
方法2
您也可以像这样在字典中搜索
entity_mapped = [mapping.get(i) for i in entities_list if i in mapping]
复杂度:O(n)
演示
In [16]: mapping = {2:5,6:8,9:87}
In [17]: entities_list = [2,6]
In [18]: print [value for (key, value) in mapping.items() if key in entities_list]
[5, 8]
In [19]: print [mapping.get(i) for i in entities_list if i in mapping]
[5, 8]
答案 1 :(得分:2)
我建议您使用map function,它可以返回将一个函数应用于列表的每个元素的迭代器。出于您的目的,函数为mapping.get
,列表为entities_list
。如果实体不是None
字典的键,它将在输出列表中插入mapping
,如下所示:
def entity_mappings(mapping, entities_list):
return map(mapping.get, entities_list)
mapping = {2:5, 6:8, 9:87}
entities_list = [2, 6, 5] # Note that 5 is not a key of mapping
print(list(entity_mappings(mapping, entities_list))) # [5, 8, None]
与生成器理解相同,提供以下内容:
def entity_mappings(mapping, entities_list):
return (mapping.get(i) for i in entities_list)
mapping = {2:5, 6:8, 9:87}
entities_list = [2, 6, 5] # Note that 5 is not a key of mapping
print(list(entity_mappings(mapping, entities_list))) # [5, 8, None]
使用映射或生成器对象之类的迭代器可以节省内存,因为如果不需要,它不会计算所有值并将其存储在内存中。相反,它一次只能产生一项。当然,做事的方式始终取决于您需要做的事情,因此您可能还希望直接使用列表,这没有问题!
答案 2 :(得分:1)
其他解决方案是:
[mapping[k] for k in set(entities_list) & set(mapping.keys())]
因为字典键是唯一列表,例如:
mapping = {'v':22, 'b': 0, 'd': 44}
entities_list = ['v', 'w', 'd']
结果是:
print([mapping[k] for k in set(entities_list) & set(mapping.keys())])
# [22, 44]