Python 3.x 如何在“a”中搜索值的组合;dict";Python中的对象
我正在尝试根据另一个列表更新/追加字典项列表 家长列表Python 3.x 如何在“a”中搜索值的组合;dict";Python中的对象,python-3.x,dictionary,Python 3.x,Dictionary,我正在尝试根据另一个列表更新/追加字典项列表 家长列表 {'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'} {'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'} {'date': '2019-03-07', 'start_time': '2019-03-07 10:31:22', 'd
{'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:31:22', 'duration': '13'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'}
{'date': '2019-03-09', 'start_time': '2019-03-09 10:31:22', 'duration': '13'}
{'date': '2019-03-10', 'start_time': '2019-03-10 10:31:22', 'duration': '13'}
{'date': '2019-03-11', 'start_time': '2019-03-11 10:31:22', 'duration': '13'}
{'date': '2019-03-12', 'start_time': '2019-03-12 10:31:22', 'duration': '13'}
新列表
{'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:31:22', 'duration': '13'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:08:21', 'duration': '5'}
{'date': '2019-03-07', 'start_time': '2019-03-07 10:14:43', 'duration': '15'}
{'date': '2019-03-09', 'start_time': '2019-03-09 10:31:22', 'duration': '13'}
{'date': '2019-03-10', 'start_time': '2019-03-10 10:31:22', 'duration': '13'}
{'date': '2019-03-11', 'start_time': '2019-03-11 10:31:22', 'duration': '13'}
{'date': '2019-03-12', 'start_time': '2019-03-12 10:31:22', 'duration': '13'}
我想用新列表中的新项目更新父列表。如您所见,后者的前两项在前者中重复。因此,我只想将最后4项(从新列表)添加到父列表
简单的方法是迭代每个新列表项,并检查它是否已经存在于父列表中
代码
for newItem in NewList:
bln_item_exists = False
for parentItem in ParentList:
if dict(newItem).get("date") == dict(parentItem).get("date") and dict(newItem).get("start_time") == dict(parentItem).get("start_time"):
bln_item_exists = True
break
if not bln_item_exists:
items_to_append.append(newItem)
我担心随着我的数据库大小的增加,性能会受到影响,有没有更有效的方法来做到这一点?您可以为»父列表«中的每个项目创建一个哈希校验和列表:
import hashlib;
import json;
hashes = {}
parent_list = [ ... ]
def createHash (item):
hash_md5 = hashlib.md5()
hash_md5.update(json.dumps(item))
return hash_md5..hexdigest()
for item in parent_list:
hashes[createHash(item)] = true
def appendList(child_list):
for item in child_list:
hash = createHash(item)
if hash is not in hashes:
hashes[hash] = true
parent_list.append(item)
基本思想是:使用json序列化对象的散列来测试相等性,这样所有属性都会隐式检查。对于这些类型的操作,我建议使用
谢谢你的解决方案@philipp。我觉得熊猫解决方案对于我的用例来说要简单得多。