Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.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 3.x 输入=元组列表,输出=字典列表_Python 3.x - Fatal编程技术网

Python 3.x 输入=元组列表,输出=字典列表

Python 3.x 输入=元组列表,输出=字典列表,python-3.x,Python 3.x,请帮助我使用python 3.7获取以下场景的代码: 我有一个元组列表作为输入,如: 方框=[(10,40,50,20),(15,40,50,20)] 我想创建一个字典列表,以便我的输出采用以下格式: [ { "top":10, "right":40, "bottom":50, "left":20 }, { "top":15, "right":40, "bottom":50, "left":20 } ] 我尝试了json.dumps(),但没有得到预期

请帮助我使用python 3.7获取以下场景的代码: 我有一个元组列表作为输入,如: 方框=[(10,40,50,20),(15,40,50,20)] 我想创建一个字典列表,以便我的输出采用以下格式:

[
 {
  "top":10,
  "right":40,
  "bottom":50,
  "left":20
 },
 {
  "top":15,
  "right":40,
  "bottom":50,
  "left":20
 }
 ]

我尝试了json.dumps(),但没有得到预期的格式

您必须循环每个元组并使用它创建一个字典

boxes = [(10,40,50,20),(15,40,50,20)]
dicts = []

for b in boxes:
    top, right, bottom, left = b
    dicts.append({'top': top, 'right': right, 'bottom': bottom, 'left': left})

print(dicts)
>>> t =  [(10,40,50,20),(15,40,50,20)]
>>> d =  []
>>> for i in t: 
...   d.append({'top': i[0], 'right': i[1], 'bottom': i[2], 'left': i[3]})
... 
>>> d
[{'top': 10, 'right': 40, 'bottom': 50, 'left': 20}, {'top': 15, 'right': 40, 'bottom': 50, 'left': 20}]


首先想到的是:

boxes = [(10,40,50,20),(15,40,50,20)]
new_boxes = []
for box in boxes:
    new_boxes.append({'top': box[0],
                      'right': box[1],
                      'bottom': box[2],
                      'left': box[3]})
print(new_boxes)

您可以在列表中循环,并可以创建dict,如下所示

final = []
for t in m_tuple_list:
  final.append({ 'top': t[0], 'bottom': t[1], 'left': t[2], 'right': t[3] })

print (final)

您可以使用
map
对列表的元素应用相同的操作

def convert(x):
    return {
  "top":x[0],
  "right":x[1],
  "bottom":x[2],
  "left":x[3]
 }

inputs = [(10,40,50,20),(15,40,50,20)]
list_dic = list(map(convert, inputs))
print(list_dic)
# output
#[{'top': 10, 'right': 40, 'bottom': 50, 'left': 20},
#{'top': 15, 'right': 40, 'bottom': 50, 'left': 20}]

这可以通过列表理解轻松完成

在下面的函数中,将输入列表中的每个值元组与键列表压缩在一起,以创建所需的键-值对,这些键-值对反过来用于初始化字典对象

keys = ["top", "right", "bottom", "left"]

def convert(list_of_tuples):
    return [dict(zip(keys, vals)) for vals in list_of_tuples]

我想这将是最快的方法-很好。喜欢这种方法看起来更好