【问题标题】:how to check whether the comma-separated value in the database is present in JSON data or not using python如何使用python检查数据库中的逗号分隔值是否存在于JSON数据中
【发布时间】:2021-08-04 14:40:17
【问题描述】:

我只需要在表格中以逗号分隔的 e_code 为基础检查 JSON 数据。 如何仅过滤用户 e_code 可用的数据 在数据库中:

id         email          age      e_codes
1.         abc@gmail       19     123456,234567,345678
2.         xyz@gmail       31     234567,345678,456789

这是我的 JSON 数据

[
  {
    "ct": 1,
    "e_code": 123456,
  },
  {
    "ct": 2,
    "e_code": 234567,
  },
{
    "ct": 3,
    "e_code": 345678,
},
{
    "ct": 4,
    "e_code": 456789,
  },
{
    "ct": 5,
    "e_code": 456710,
  }
]

【问题讨论】:

  • 您需要同时导入 CSV 数据和 JSON 数据,然后进行比较。你都尝试了些什么?有代码吗?
  • 是的,先生,我已经加载了 JSON 文件,并且还使用 cursor.fetchall 获取了数据库。另外,我必须将过滤后的数据发送到相应的电子邮件 ID
  • 您能否编辑您的问题以包含代码,以便我们查看您遇到的困难?
  • 是的,@Axe319 等等

标签: python arrays json python-3.x csv


【解决方案1】:

如果效率不是问题,您可以遍历表,使用case['e_codes'].split(',') 将值拆分到列表中,然后对每个代码循环遍历 JSON 以查看它是否存在。 如果您的数据、JSON 或值的数量很长,这可能会有点低效。

最好先创建一个查找字典,其中代码是键:

lookup={}
for e in my_json:
    lookup[e['e_code']] = 1

然后您可以检查表中有多少代码实际上在 JSON 中:

## Let's assume that the "e_codes" cell of the 
## current line is data['e_codes'][i], where i is the line number

for i in lines:
    match = [0,0]
    for code in data['e_codes'][i].split(','):
        try:
            match[0]+=lookup[code]
            match[1]+=1
        except:
            match[1]+=1

    if match[1]>0: share_present=match[0]/match[1]

对于每种情况,您都会得到一个share_present,如果所有代码都出现在 JSON 中,则为 1.0,如果没有任何代码出现,则为 0.0,并且介于两者之间的某个值表示存在的代码的份额。根据您保留案例的阈值,您可以根据此值将过滤器设置为 TrueFalse

【讨论】:

  • 非常感谢您,Martin Wettstein,我会检查并通知您,
猜你喜欢
  • 1970-01-01
  • 2018-03-11
  • 2011-11-30
  • 1970-01-01
  • 2019-12-16
  • 1970-01-01
  • 2012-07-02
  • 1970-01-01
  • 2010-10-18
相关资源
最近更新 更多