我试图想象如何从不同的路径导入大字典列表。我想在不同的文件上使用字典,这样我的程序在处理时可能看起来更整洁。
import heapq
x = raw_input()
y = raw_input()
def shortestPath(start, end):
queue,seen = [(0, start, [])], set()
while True:
(cost, v, path) = heapq.heappop(queue)
if v not in seen:
path = path + [v]
seen.add(v)
if v == end:
return cost, path
for (next, c) in graph[v].iteritems():
heapq.heappush(queue, (cost + c, next, path))
graph = {
'a': {'w': 16, 'x': 9, 'y': 11},
'b': {'w': 11, 'z': 8},
'w': {'a': 16, 'b': 11, 'y': 4},
'x': {'a': 9, 'y': 12, 'z': 17},
'y': {'a': 11, 'w': 4, 'x': 12, 'z': 13},
'z': {'b': 8, 'x': 17, 'y': 13},
}
cost, path = shortestPath(x, y)
print cost
所以这是我所说的小字典的程序的一部分,但我在另一个文件上做得更大。我想删除小字典并从另一个文件导入更大的图形。另一个文件叫做Graph.py
答案 0 :(得分:2)
你的main.py
import heapq
import Graph
x = raw_input()
y = raw_input()
def shortestPath(start, end):
queue,seen = [(0, start, [])], set()
while True:
(cost, v, path) = heapq.heappop(queue)
if v not in seen:
path = path + [v]
seen.add(v)
if v == end:
return cost, path
for (next, c) in graph[v].iteritems():
heapq.heappush(queue, (cost + c, next, path))
graph = Graph.graph
cost, path = shortestPath(x, y)
print cost
你的Graph.py
graph = {
'a': {'w': 16, 'x': 9, 'y': 11},
'b': {'w': 11, 'z': 8},
'w': {'a': 16, 'b': 11, 'y': 4},
'x': {'a': 9, 'y': 12, 'z': 17},
'y': {'a': 11, 'w': 4, 'x': 12, 'z': 13},
'z': {'b': 8, 'x': 17, 'y': 13},
}#add your complex dictionary
您可以从Graph.py中导入图形,如变量。
答案 1 :(得分:1)
在第一个文件file_1
中创建一个包含字典定义的类作为属性:
class myDictionary():
def __init__(self):
self.dictionary = {'a': {'w': 16, 'x': 9, 'y': 11},
'b': {'w': 11, 'z': 8},
'w': {'a': 16, 'b': 11, 'y': 4},
'x': {'a': 9, 'y': 12, 'z': 17},
'y': {'a': 11, 'w': 4, 'x': 12, 'z': 13},
'z': {'b': 8, 'x': 17, 'y': 13},}
def getDictionary(self):
return self.dictionary
然后在第二个文件file_2
中,只需创建一个类的实例并调用将返回字典的函数。
import file_1
graph = file_1.myDictionary().getDictionary()
答案 2 :(得分:0)
您可以考虑以普及的json格式存储数据,并将其导入为
import json
import sys
def main(fn):
with open(fn) as f:
graph = json.load(f)
x = raw_input()
y = raw_input()
cost, _ = shortest_path(graph, x, y)
print cost
def shortest_path(graph, x, y):
# .... Your code. Notice that i've given graph as an argument here
if __name__ == '__main__':
main(sys.argv[1])
然后像你一样运行你的脚本
python yourscript.py mygraph.json
mygraph.json的位置如下:
{
"a": {
"y": 11,
"x": 9,
"w": 16
},
"b": {
"z": 8,
"w": 11
},
"w": {
"a": 16,
"y": 4,
"b": 11
},
"y": {
"a": 11,
"x": 12,
"z": 13,
"w": 4
},
"x": {
"a": 9,
"y": 12,
"z": 17
},
"z": {
"y": 13,
"x": 17,
"b": 8
}
}