使用pandas从两个列表创建JSON数组

aiqt4smr  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(78)

可以将两个列表压缩到一个JSON数组中吗?
输入:

keys=["['os','dist','rel','flag']",
          "['os','dist']",
          "['os','dist','rel']",
          "['os','version','rel','flag']"]
    vals=["['linux','centos','9','y']",
         "['linux','ubuntu']",
         "['linux','rhel','8']",
         "['linux','8','.03','y']"]
    df=pd.DataFrame({'key':keys,'val':vals})

字符串
所需输出:

{'key':'os','val':'linux'},{'key':'dist','val':'rhel'},{'key':'rel','val':'9'},{'key':'flag','val':'y'}
...
...


我是python新手,尝试了几种不同的list/map/lambda/zip组合,到目前为止都没有成功。

kcugc4gi

kcugc4gi1#

这是可以做到的,但你肯定不需要或想要Pandas。我的猜测是,这不是你想要的实际结果,但这里是如何做到这一点。

import ast

keys=["['os','dist','rel','flag']",
      "['os','dist']",
      "['os','dist','rel']",
      "['os','version','rel','flag']"]
vals=["['linux','centos','9','y']",
     "['linux','ubuntu']",
     "['linux','rhel','8']",
     "['linux','8','.03','y']"]

keys = [ast.literal_eval(k) for k in keys]
vals = [ast.literal_eval(v) for v in vals]

results = [] 
for kk,vv in zip(keys, vals):
    results.extend( [{'key': k, 'val': v} for k,v in zip(kk,vv)] )

from pprint import pprint
pprint(results)

字符串
输出量:

[{'key': 'os', 'val': 'linux'},
 {'key': 'dist', 'val': 'centos'},
 {'key': 'rel', 'val': '9'},
 {'key': 'flag', 'val': 'y'},
 {'key': 'os', 'val': 'linux'},
 {'key': 'dist', 'val': 'ubuntu'},
 {'key': 'os', 'val': 'linux'},
 {'key': 'dist', 'val': 'rhel'},
 {'key': 'rel', 'val': '8'},
 {'key': 'os', 'val': 'linux'},
 {'key': 'version', 'val': '8'},
 {'key': 'rel', 'val': '.03'},
 {'key': 'flag', 'val': 'y'}]

相关问题