我正试图在字典中找到匹配的名字。用户发送的请求如下所示:
req= [{"host":"usr1"}, {"host":"usr7"}, {"host":"usr10"}, {"host":"usr11"}, {"host":"usrx...."}, ..../more hosts]然后,我在另一个字典中检查匹配情况,该字典如下所示:
data = [
{
"host": "usr1",
"address": "x"
},
{
"host": "usr2",
"address": "y"
},
{
"host": "usr3",
"address": "z"
}
.../ more hosts
]如果来自用户的请求与数据库之间存在匹配,我想弹出该主机。我试过这样做:
new_static = []
for x, i in zip(data, req):
if i['host'] != x['host']:
new_static.append(x)
data = new_static
continue它可以工作,但是这里出现了一个问题,如果req的len和数据不相等,我也尝试了双嵌套循环,但没有成功。
发布于 2022-06-22 13:13:53
您可以尝试使用以下嵌套循环解决方案:
req= [{"host":"usr1"}, {"host":"usr7"}, {"host":"usr10"}, {"host":"usr11"}]
data = [
{
"host": "usr1",
"address": "x"
},
{
"host": "usr2",
"address": "y"
},
{
"host": "usr3",
"address": "z"
}]
for i in req:
for j in data:
if i["host"] == j["host"]:
print("Host: ", i["host"])输出:
Host: usr1发布于 2022-06-22 13:14:42
假设请求中的对象只包含一个键,则可以将其简化为set以提高效率。然后,假设您希望过滤data的元素,这些元素的host不在req中,这可以通过以下方法实现:
hosts_request = set(el['host'] for el in req)
filtered_data = [entry for entry in data if entry['host'] not in hosts_request]发布于 2022-06-22 13:15:44
sinmple = [e["host"] for e in data]
for r in req:
if r["host"] in simple:
pass
# do something with the duplicathttps://stackoverflow.com/questions/72716059
复制相似问题