python-2.7 - AttributeError: 'dict' 迭代集合字典时对象没有属性 (...)

标签 python-2.7 graph pycharm attributeerror

我试图从邻接列表表示的无向图中删除一个节点,但收到一个我无法理解的错误。

ugraph 示例:

g1 = {0: set([1]), 1: set([0, 2]), 2: set([1, 3]), 3: set([2]), 4: {5, 6}, 5: {4}, 6: {}}

我正在创建的函数:

def remove_node(ugraph, node):
    """
    :param ugraph: An undirected graph
    :param node: The node that we want to remove
    :return: The undirected graph minus one node :)
    """

    try:
        del ugraph[node]
    except KeyError:
        print "The node is not in the graph" 

    for key in ugraph.keys():
        ugraph[key] = ugraph[key].difference(set([node]))

    return ugraph

这是我的错误:

Traceback (most recent call last):
  File "/home/juan/PycharmProjects/AlgorithmicThinking_week2/resilence.py", line 46, in <module>
    print remove_node(g1, 1)
  File "/home/juan/PycharmProjects/AlgorithmicThinking_week2/resilence.py", line 42, in remove_node
    ugraph[key] = ugraph[key].difference(set([node]))
AttributeError: 'dict' object has no attribute 'difference'

为什么会发生这种情况?

最佳答案

其中一个与另一个不同:

>>> g1 = {0: set([1]), 1: set([0, 2]), 2: set([1, 3]), 3: set([2]), 4: {5, 6}, 5: {4}, 6: {}}
>>> for key in g1: 
...     print key, g1[key], type(g1[key])
...
0 set([1]) <type 'set'>
1 set([0, 2]) <type 'set'>
2 set([1, 3]) <type 'set'>
3 set([2]) <type 'set'>
4 set([5, 6]) <type 'set'>
5 set([4]) <type 'set'>
6 {} <type 'dict'>

{} 是一个空字典,而不是空集。请改用 set()

关于python-2.7 - AttributeError: 'dict' 迭代集合字典时对象没有属性 (...),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31085293/

相关文章:

python - 使用 Beautiful Soup 从非类部分获取数据

C++ VERTEX 和 EDGE 类不起作用

javascript - 多个X轴标签谷歌图表

python - PyCharm 在 vi​​rtualenv 中找不到包

python - Django教程错误: Setting up the test client

python-2.7 - 计数分数

Python从pandas数据框中删除停用词给出错误的输出

每个线程使用不同设置的 Python 多线程

java - 检查权重总和不为 0 的循环

python - 运行unittest.main()时为"No tests were found"