只需添加数据库差异data_out - 数据库。
如何只从data_out(常规刷新)向数据库添加新闻,而数据库没有这个数据? 在db中必须没有重复!
database = [
{ id: 1, name: 'steve', age: '18'},
{ id: 2, name: 'margo', age: '17'},
{ id: 3, name: 'sten', age: '19'}
]
data_from_out = [
{ name: 'steve', age: '18'},
{ name: 'margo', age: '17'},
{ name: 'sten', age: '19'},
{ name: 'janifer', age: '21'},
{ name: 'mary', age: '21'}
]
按名称/标题差异(此uniq参数),并仅添加到数据库差异
添加到DB =>
{ "name": 'janifer', "age": '21'},
{ "name": 'mary', "age": '21'}
.
def compare_diff(arr_in, arr_database, check_tag):
try:
db_records = {d[check_tag] for d in arr_database}
data_from_out_records = {d[check_tag] for d in arr_in}
# set difference
diff = data_from_out_records - data_from_out_records & db_records
# make array from diff set
diff = [d for d in data_from_out_records if d[check_tag] if diff]
return diff
except:
print('Error in compare_diff. File file.py.')
答案 0 :(得分:0)
您所描述的diff
是data_from_out_records
和db_records
之间的设置差异
db_records = {d["name"] for d in database}
data_from_out_records = {d["name"] for d in data_from_out}
diff = data_from_out_records - data_from_out_records & db_records
diff = [d for d in data_from_out if d["name"] if diff]
答案 1 :(得分:0)
工作代码=>
def compare_diff(arr_in, arr_database, check_tag):
try:
db_records = {d[check_tag] for d in arr_database}
data_from_out_records = {d[check_tag] for d in arr_in}
# set difference
diff = data_from_out_records - (data_from_out_records & db_records)
# make array from diff set
diff_arr = [d for d in arr_in if d[check_tag] in diff]
return diff_arr
except:
print('Error in compare_diff')
return False
感谢@ Uri-Goren的帮助。