【问题标题】:How to find the first node of the tree in a dict?如何在字典中找到树的第一个节点?
【发布时间】:2017-12-05 21:54:18
【问题描述】:

我有一个大问题,在开始工作的函数中我需要找到树中的第一个节点,这里是一个例子:

              "hi"
            /     \
           /       \
          "ok"     "no"
          /
         /
       "lol"

问题是我不知道如何从 dict 中获取它,因为输入是这样的:

{ "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }

所以在这种情况下,“hi”是第一个,因为在 dict.values() 中没有人有“hi”,问题是怎么说,最重要的是 dict 有 50'000 个节点,所以如果我一个一个检查它加班了。

我写了这个:

    d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
    x = d.values()
    x = str(x)
    for y in d.keys():
        if not y in x :
            first_node = y
            break

但问题是它可以是像“hello”这样的词和像“hell”这样的“key”,所以“hell”在“hellow”中但不是“hellow”:(

【问题讨论】:

  • 你好不是你好抱歉
  • 您可以(并且应该)编辑您的问题

标签: python dictionary tree nodes


【解决方案1】:

这是一种使用set.difference 的方法。

from itertools import chain

d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : [] }
roots = set(d).difference(chain.from_iterable(d.values()))

给我们

{'hi'}

【讨论】:

  • 但如果我有这个列表:{'bellissimanon': ['cio', 'cia'], 'cio': [], 'belissima': ['belissimanon'], 'cia' : []} 他回馈 {'belissima', 'bellissimanon'} ,但应该只是“bellissima”
  • @AliToccacieli 你有两个不同的belissimanon 拼写是故意的吗?
  • 是的,这是一个拼写错误,因此您有 2 个起始节点
  • 我的错误,它非常有效,因为所有的练习都是正确的,只有当第一个节点不按顺序时结果不同但现在是好的 tnx ^.^ 最好!!!!
【解决方案2】:

您可以使用列表推导:

d = { "ok":["lol"] , "no":[] , "hi":["ok","no"] , "lol" : [] }
root = [a for a, b in d.items() if all(a not in d for c, d in d.items())][0]

输出:

'hi'

【讨论】:

  • 和我写的字典一样的问题:d = {"bellissimanon":["cio","cia"],"cio":[],"belissima["belissimanon "],"cia":[]} 他给我们回馈:'bellissimanon' 如果你把 [1] "bellissima" 表示 2 结果
【解决方案3】:

您可以选择一个随机节点并跟随它到顶部。 我刚刚写了一些东西,我会计时并报告结果:

d = { "ok":["lol"] , "no":[] , "hi": ["ok","no"] , "lol" : []}

node = list(d.keys())[0]
found = False
while not found:
    found = True
    for key, value in d.items():
        if node in value:
            node = key
            found = False

print(node)

事实证明我的解决方案在测试环境中表现最好:

**10 nodes**
0.0000020000017 s - my solution
0.0000043555594 s - using set.diffrence by Patrick Haugh
0.0001111112098 s - list comprehension by Ajax1234

**1000 nodes**
0.0007560006720 s - my solution
0.0015977791980 s - using set.diffrence by Patrick Haugh
0.3337478522203 s - list comprehension by Ajax1234

**10000 nodes**
0.0077213401967 s - my solution
0.0138804567826 s - using set.diffrence by Patrick Haugh
35.264710457520 s - list comprehension by Ajax1234

【讨论】:

  • 无论如何我都做到了 tnx,我也会试试这个,看看女巫对每个人来说都更快 tnx:D
  • 我的是最快的,但是set.diffrence找到了所有的根
猜你喜欢
  • 2020-11-26
  • 1970-01-01
  • 2015-08-02
  • 1970-01-01
  • 2013-02-20
  • 1970-01-01
  • 2015-08-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多