Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.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数组_Python_Multidimensional Array_Dictionary - Fatal编程技术网

来自键集的Python数组

来自键集的Python数组,python,multidimensional-array,dictionary,Python,Multidimensional Array,Dictionary,我需要基于包含键的数组在python中创建数组/字典。 我找到了一个。不幸的是,我不知道如何在Python中实现这一点。有人能给我一些提示吗 a = ['one', 'two', 'three'] b = ['one', 'four', 'six'] 我希望得到以下结果: c = {'one': {'two': 'three', 'four': 'six}} PHP解决方案为此使用了引用。也许这是一个更好的例子: ar[0] = ['box0', 'border0', 'name'] var

我需要基于包含键的数组在python中创建数组/字典。 我找到了一个。不幸的是,我不知道如何在Python中实现这一点。有人能给我一些提示吗

a = ['one', 'two', 'three']
b = ['one', 'four', 'six']
我希望得到以下结果:

c = {'one': {'two': 'three', 'four': 'six}}
PHP解决方案为此使用了引用。也许这是一个更好的例子:

ar[0] = ['box0', 'border0', 'name']
var[1] = ['box0', 'border0', 'type']
var[2] = ['box0', 'border1', 'name']
var[3] = ['box1', 'border2', 'name']
var[4] = ['box1', 'border0', 'color']

$val = 'value'
在PHP中,结果如下所示:

$result = array(
    'box0' => array(
      'border0' => array('name' => $val, 'type' => $val, 'color' => $val), 
      'border1' => array('name' => $val),
    ),
    'box1' => array(
      'border0' => array('color' => $val),
      'border2' => array('name' => $val)
    )
) );

PHP应答从键的路径构造一个字典。在Python中有一个等价物:

from collections import defaultdict
def set_with_path(d, path, val):
    end = path.pop()
    for k in path:
        d = d.setdefault(k, {})
    d[end] = val
例如:

>>> d = {}
>>> set_with_path(d, ['one', 'two', 'three'], 'val')
>>> d
{'one': {'two': {'three': 'val'}}}
>>> set_with_path(d, ['one', 'four', 'six'], 'val2')
>>> d
{'one': {'four': {'six': 'val2'}, 'two': {'three': 'val'}}}

这将产生
{'one':['two','three','four','six']}
。这个问题的措辞让我相信他想要一个列表字典。这是严格针对键、子键和值的三元组的情况,还是你试图将其推广到长度为N的列表?相关:键的N元组是可能的。这只是一个例子,就是这样!非常感谢;-)
>>> d = {}
>>> set_with_path(d, ['one', 'two', 'three'], 'val')
>>> d
{'one': {'two': {'three': 'val'}}}
>>> set_with_path(d, ['one', 'four', 'six'], 'val2')
>>> d
{'one': {'four': {'six': 'val2'}, 'two': {'three': 'val'}}}