数据库的搜索模拟
教学用方案
# # 查找
# # 假设数据库中取出来的数据为以下的内容:
database = [{"name": "zs", "age": 18}, {"name": "zs2", "age": 28}, {"name": "zs", "age": 18}]
# # 查询条件为
cond = {"age": 18, "name":"zs"}
# cond = {"age": 18}
# cond = {"age": 18, "gender":1}
# # 写一套逻辑,可以让database经过一翻处理,得到这样的结果
# res = [{"name": "zs", "age": 18}, {"name": "zs3", "age": 18}]
for data in database:
print("*"*20)
print(data)
# 获得一个又一个的字典
# data = {"name": "zs", "age": 18}
# 判断1,条件中的键是否在data字典中
num = 0 # 计数器,统计有几个符合条件
cond_num = len(cond) # 有几个条件
for k, v in cond.items():
if k in data and data[k] == v:
num += 1
print("{}-{}".format(num, cond_num), data, k,v)
else:
if num == cond_num:
# 判断达到条件的数量与要求的条件数量是否一致
print(data, '=='*10)
方案
# # 查找
# # 假设数据库中取出来的数据为以下的内容:
database = [{"name": "zs", "age": 18}, {"name": "zs2", "age": 28}, {"name": "zs", "age": 18}]
# # 查询条件为
cond = {"age": 18, "name":"zs"}
for data in database:
flag = True
for k, v in cond.items():
if k in data and data[k] == v:
# print(data, k, v)
pass
else:
flag = False
else:
if flag:
print(data, '===>')