【问题标题】:Dictionary with nested categories from a single list具有来自单个列表的嵌套类别的字典
【发布时间】:2017-09-29 11:31:24
【问题描述】:

我有一个结构如下的列表:

arr = [ ['a'],
                ['a','b'],
                ['a','x','y'],
                ['a','c'],
                    ['a','c','a'],
                    ['a','c','b'],
                        ['a','c','b','a'],
                        ['a','c','b','b'],
                ['a','d'],
            ['b'],
                ['b','c'],
                    ['b','c','a'],
                    ['b','c','b'],                  
            ['c','d'],
                ['c','d','e'],
                ['c','d','f'],
                    ['c','d','f','a'],
                    ['c','d','f','b'],
                        ['c','d','f','b','a'],
                ]

正如您所观察到的,列表有一些独特的元素,随后的元素会在独特元素的基础上构建,直到出现新的独特元素。这些应该是类别和子类别。因此 [a] , [b] , ['c','d'] 是广义的主要类别,然后基于与上述相同的原则,在子类别中还有进一步的子类别。理想情况下,我希望将类别和子类别作为字典。最终结果应该类似于:

{'a': ['a-b',
     'a-x-y',
     {'a-c': 
           ['a-c-a',
            {'a-c-b':
                    ['a-c-b-a', 
                     'a-c-b-b']
            }]
     }
    ],
'b' : ................
'c-d': ...............}

我也可以只使用第一级子分类,而完全放弃其余的。在这种情况下,输出将是:

{'a': ['a-b', 'a-x-y', 'a-c', 'a-d'], 'b': ['b-c'], 'c-d': ['c-d-e', 'c-d-f']}

我已经为第二种情况编写了代码,但我不确定这是否是解决此问题的可靠方法:

def arrange(arr):
cat = {"-".join(arr[0]): ["-".join(arr[1])]}
main = 0
for i in range(2,len(arr)):
    l = len(arr[main])
    if arr[main] == arr[i][0:l]:
        cat["-".join(arr[main])].append("-".join(arr[i]))
    else:
        cat["-".join(arr[i])] = []
        main = i
for k,v in cat.items():
    found = True
    i = 0
    while i < len(v)-1:
        f_idx = i + 1
        while  v[i] in v[f_idx]:
            v.pop(f_idx)
        i += 1
return cat

输出-:

{'a': ['a-b', 'a-x-y', 'a-c', 'a-d'], 'b': ['b-c'], 'c-d': ['c-d-e', 'c-d-f']}

请帮助我改进此代码,或者帮助我使用具有完整结构的字典,其中包含所有子分类。谢谢

【问题讨论】:

  • 当我使用您的示例输入数据运行此函数时,它会返回 None。你能显示你得到的输出吗?
  • 糟糕,最后忘记了返回猫。可能就是这样。当我运行它时,我得到 {'a': ['a-b', 'ax-y', 'a-c', 'a-d'], 'b': ['b-c'], ' cd': ['cd-e', 'cd-f']}
  • 至少对于您提供的输入大小,我会说这非常强大。您可以在放大输入大小时使用此方法来分析函数:gist.github.com/JacobIRR/318143230a6ced24ce82882079b7ae10 lenjoin 最常使用。
  • 我明白了.. 谢谢。关于如何制作包含所有子类别的字典的任何想法?
  • 我会一直盯着它看,但我还不明白缩进是怎么回事以及它如何影响输出

标签: python algorithm list dictionary nested


【解决方案1】:

最后,我相信我已经拥有了您所说的第一级子分类,并完全丢弃了其余部分。

诀窍是根据列表中的项目(键)不是后续项目(值)的子列表来创建操作。
删除重复项使用了相同的逻辑。

from collections import defaultdict

#Function that compares two lists even with duplicate items
def contains_sublist(lst, sublst):
    n = len(sublst)
    return any((sublst == lst[i:i+n]) for i in xrange(len(lst)-n+1))

#Define default dict of list
aDict = defaultdict(list)
it = iter(arr)

#Format key 
key = '-'.join(next(it))
s = list(key)

# Loop that collects keys if key is not sublist else values
for l in it:
    if contains_sublist(l, s):
        aDict[key].append(l)
    else:
        key = '-'.join(l)
        s = l

#Loop to remove duplicate items based upon recurrance of sublist
it = iter(aDict.keys())
for k in it:
    dellist = []

    for s in aDict[k]:
        for l in aDict[k]:
            if l != s:
                if contains_sublist(l, s):
                    if not l in dellist:        
                        dellist.append(l)
    for l in dellist:        
        try:
            aDict[k].remove(l)
        except ValueError:
            pass

#Create final dict by concatenating list of list with '-'
finaldict = {k:[ '-'.join(i) for i in v ] for k,v in aDict.iteritems()}

结果:

Python 2.7.9 (default, Dec 10 2014, 12:24:55) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
>>> finaldict
{'a': ['a-b', 'a-x-y', 'a-c', 'a-d'], 'b': ['b-c'], 'c-d': ['c-d-e', 'c-d-f']}
>>> 

【讨论】:

  • 感谢@Anil 花时间编写代码。我会在晚上看看它。同时,我进一步压缩了我的解决方案。随意看看。
【解决方案2】:

您正在描述Trie

这是一个非常基本的实现:

def make_trie(words):
   root = dict()
   for word in words:
       current_dict = root
       for letter in word:
           current_dict = current_dict.setdefault(letter, {})
       current_dict[1] = 1
   return root

trie = make_trie(arr)
print(trie)
# {'a': {1: 1, 'c': {'a': {1: 1}, 1: 1, 'b': {'a': {1: 1}, 1: 1, 'b': {1: 1}}}, 'b': {1: 1}, 'd': {1: 1}, 'x': {'y': {1: 1}}}, 'c': {'d': {1: 1, 'e': {1: 1}, 'f': {'a': {1: 1}, 1: 1, 'b': {'a': {1: 1}, 1: 1}}}}, 'b': {1: 1, 'c': {'a': {1: 1}, 1: 1, 'b': {1: 1}}}}
print(trie.get('a',{}).get('x',{}))
# {'y': {1: 1}}

这个 trie 只是嵌套的字典,因此很容易迭代 ['a', 'x'] 的所有子代或选择所有最大深度为 2 的字典。

1 用于叶词:例如,如果您有 ['a', 'x', 'y'] 作为子数组,但没有 ['a', 'x']

有更完整的 Python Trie 库,如pygtrie

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-19
    • 1970-01-01
    • 2015-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多