如何将垂直阵列迁移到水平阵列?

2024-04-19 23:35:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python2;如何将数组迁移到多个维度?示例:

a = ['a', 'b', 'c', ...]

收件人:

foo['a']['b']['c']...

并检查是否存在,例如有多个数组:

a = ['a', 'b', 'c']
b = ['a', 'x', 'y']

结果是:

foo['a'] -> ['b'], ['x']
foo['a']['b'] -> ['c']
foo['a']['x'] -> ['y']

我需要这个做一个文件目录树导航,为每个路径发现需要添加路径和文件,路径是从数据库获取。需要单独的导航示例:

http://foo.site/a ->
    /b
    /c
    /d

http://foo.site/a/b ->
    /file1.jpg
    /file2.jpg

对于每个路径,使用/进行拆分,并需要使用每个路径和文件生成多维数组或字典。你知道吗


Tags: 文件路径数据库http示例字典foosite
2条回答

此解决方案适用于我使用eval和Dictionaries of dictionaries merge

def __init__(self):
    self.obj = {}

def setPathToObject(self, path):
    path_parts = path.replace('://', ':\\\\').split('/')
    obj_parts  = eval('{ \'' + ('\' : { \''.join(path_parts)) + '\' ' + ('}' * len(path_parts)))
    obj_fixed  = str(obj_parts).replace('set([\'', '[\'').replace('])}', ']}').replace(':\\\\', '://')
    obj        = eval(obj_fixed)
    self.obj = self.recMerge(self.obj.copy(), obj.copy())
    return obj

def recMerge(self, d1, d2):
    for k, v in d1.items():
        if k in d2:
            if all(isinstance(e, MutableMapping) for e in (v, d2[k])):
                d2[k] = self.recMerge(v, d2[k])
            elif all(isinstance(item, list) for item in (value, dict2[key])):
                d2[key] = v + d2[k]
    d3 = d1.copy()
    d3.update(d2)
    return d3

测试:

setPathToObject('http://www.google.com/abc/def/ghi/file1.jpg')
setPathToObject('http://www.google.com/abc/xyz/file2.jpg')
setPathToObject('http://www.google.com/abc/def/123/file3.jpg')
setPathToObject('http://www.google.com/abc/def/123/file4.jpg')
print self.obj

> { 'http://www.google.com': { 'abc': { 'def': { 'ghi': [ 'file1.jpg' ], '123': [ 'file3.jpg', 'file4.jpg' ] }, 'xyz': [ 'file2.jpg' ] } } }

在Python2上工作。你知道吗

你问的不太清楚

不过,您可以定义一个简单的树结构,如下所示:

import collections

def tree():
    return collections.defaultdict(tree)

使用方法如下:

foo = tree()
foo['a']['b']['c'] = "x"
foo['a']['b']['d'] = "y"

你会得到:

defaultdict(<function tree at 0x7f9e4829f488>,
            {'a': defaultdict(<function tree at 0x7f9e4829f488>,
                              {'b': defaultdict(<function tree at 0x7f9e4829f488>,
                                                {'c': 'x',
                                                 'd': 'y'})})})

类似于:

{'a': {'b': {'c': 'x', 'd': 'y'})})})

编辑

但是您还要求“为每个路径创建一个splitby/并需要为每个路径和文件创建多维数组或字典。”

我通常使用os.walk搜索目录中的文件:

import os
import os.path


start_dir = ".."

result = {}
for root, filenames, dirnames in os.walk(start_dir):
    relpath = os.path.relpath(root, start_dir)
    result[relpath] = filenames

相关问题 更多 >