Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将输出获取为json而不是数组_Python_Arrays_Json_Python 2.7_Python 3.x - Fatal编程技术网

Python 将输出获取为json而不是数组

Python 将输出获取为json而不是数组,python,arrays,json,python-2.7,python-3.x,Python,Arrays,Json,Python 2.7,Python 3.x,我正在尝试将输入与我创建的名称数组相匹配。下面是它的代码: >>> from fuzzywuzzy import process >>> names = ["Adam Gilchrist","Adam Barbar","Adam lobiof","Jaffer Wilson","Janet Wilson","Jane Cold"] >>> process.extract('adamgilchrist',names) [('Adam Gilch

我正在尝试将输入与我创建的名称数组相匹配。下面是它的代码:

>>> from fuzzywuzzy import process
>>> names = ["Adam Gilchrist","Adam Barbar","Adam lobiof","Jaffer Wilson","Janet Wilson","Jane Cold"]
>>> process.extract('adamgilchrist',names)
[('Adam Gilchrist', 84), ('Adam lobiof', 50), ('Jane Cold', 50), ('Adam Barbar', 40), ('Janet Wilson', 30)]
我得到的只是一系列的名字和信心

我想将输出显示为json,如下所示:

{
  "results": [
    {
      "name": "Adam Gilchrist",
      "confidence": 84
    },
    {
      "name": "Adam lobiof",
      "confidence": 50
    },
    {
      "name": "Jane Cold",
      "confidence": 50
    },
    {
      "name": "Adam Barbar",
      "confidence": 40
    },
    {
      "name": "Janet Wilson",
      "confidence": 30
    }
  ]
}

我在windows 10系统中使用python 2.7

您可以将元组解包与列表理解结合使用,以实现以下目的:

...
result = process.extract('adamgilchrist',names)
result = [{"name": name, "confidence": confidence} for name, confidence in result]
导致

[{'confidence': 84, 'name': 'Adam Gilchrist'}, {'confidence': 50, 'name': 'Adam lobiof'}, {'confidence': 50, 'name': 'Jane Cold'}, {'confidence': 40, 'name': 'Adam Barbar'}, {'confidence': 30, 'name': 'Janet Wilson'}]
您只需稍作调整即可获得最终结果(如有必要):

{'result': results}
那又是什么呢

{'result': [
    {'confidence': 84, 'name': 'Adam Gilchrist'},
    {'confidence': 50, 'name': 'Adam lobiof'}, 
    {'confidence': 50, 'name': 'Jane Cold'}, 
    {'confidence': 40, 'name': 'Adam Barbar'}, 
    {'confidence': 30, 'name': 'Janet Wilson'}]
}