Skip to main content
 首页 » 编程设计

python之在 Python 2 vs 3 中将图形渲染为带有集合列表的字典时出现问题

2025年01月19日27powertoolsteam

这是一个 2 伙伴。

以下代码在 Python 2 中。它将图形呈现为字典,值作为包含列表的集合。

import urllib2 
 
CITATION_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_phys-cite.txt" 
 
def load_graph(graph_url): 
 
    graph_file = urllib2.urlopen(graph_url) 
    graph_text = graph_file.read() 
    graph_lines = graph_text.split('\n') 
    graph_lines = graph_lines[ : -1] 
 
    print "Loaded graph with", len(graph_lines), "nodes" 
 
    answer_graph = {} 
    for line in graph_lines: 
        neighbors = line.split(' ') 
        node = int(neighbors[0]) 
        answer_graph[node] = set([]) 
        for neighbor in neighbors[1 : -1]: 
            answer_graph[node].add(int(neighbor)) 
 
    return answer_graph 

示例输出:{1001: set([9304045, 9308122]), 1002: set([9201007, 9204031, 9210123, 9912187]), ...

以上代码针对 Python 3 进行了更新。负责渲染图形的部分保持不变:

answer_graph = {} 
for line in graph_lines: 
    neighbors = line.split(' ') 
    node = int(neighbors[0]) 
    answer_graph[node] = set([]) 
    for neighbor in neighbors[1 : -1]: 
        answer_graph[node].add(int(neighbor)) 
 
return answer_graph 

示例输出:{9306112: {9210128, 1, 9202065}, 9306114: {1, 9204065, 9301122} ...}

1) 为什么 node: set([1, 2, 3]) 符号即使嵌入到代码中也会消失?

2) 我尝试将 answer_graph[node].add(int(neighbor)) 更改为 answer_graph[node].add([int(neighbor)]) 以让列表出现在集合中。我收到错误 TypeError: unhashable type: 'list'。这是目前让我感到极度困惑的一点。我在这里看到过建议集不能包含列表的帖子。这显然是错误的,因为我已经用这种方式表示了图表。也就是说,当我尝试将列表添加到集合时,它只是向我抛出一个错误。

关于这两个问题,我遗漏了什么?

请您参考如下方法:

这就是 Python 2 和 3 中打印集合的方式。3 个元素的集合 1, 2, 3 在 Python 2 中打印为

set([1, 2, 3]) 

在 Python 3 中,它被打印为

{1, 2, 3} 

所以 set([9304045, 9308122]) 是两个元素 9304045, 9308122 的集合,而不是列表 [9304045, 9308122] 作为一个元素。