我正在一個新的 TI-84 Python 版計算器上撰寫 Python 代碼。這些計算器使用 CircuitPython 的一個版本,對一些相當基本的功能支持有限。
這包括缺少字典方法,如 items() 和 values()。
下面是我的Dijkstra演算法的原始版本,接下來是TI-Python中的一個幾乎完整的版本。我在轉換最后兩個items()實體時遇到了困難,因為它們是可以作業的替代品。
nodes = ('A'/span>, 'B'/span>, 'C'/span>, 'D'/span>, 'E'/span>)
距離 = {
'A'/span>: {'B'/span>: 6, 'D': 1}。
'B'/span>: {'A'/span>: 6, 'C': 5, 'D': 2, 'E' :2},
'C'/span>: {'B'/span>: 5, 'E': 5}。
'D'/span>: {'A'/span>: 1, 'B': 2, 'E'/span>: 1}。
'E'/span>: {'B'/span>: 2, 'C': 5, 'D'/span>: 1}}
unvisited = {node: None for node in nodes}。#using None as inf
visited = {}
current = 'A' #起始節點
currentDistance =0
unvisited[current] = currentDistance
while True:
# 對于與當前節點相鄰的節點來說。
for neighbour, distance in distances[current].items() 。
# ignore if already visited[/span].
if鄰居 not in unvisited:
繼續
#計算到這個新節點的總距離。
newDistance = currentDistance distance
# 如果這個相鄰的節點有一個更低的距離if unvisited[neighbour] is None or unvisited[neighbour] > newDistance:
# update distance to this new, lower distance[/span
unvisited[neighbour] = newDistance
# 將當前節點和從起點開始的距離添加到訪問串列中。
visited[current] = currentDistance
# 將當前節點從未訪問串列中移除
del unvisited[current]。
# If all nodes have been visited del unvisited[current].
if not unvisited:
# exit[/span]。
break
# candidate for next node to visit
print(unvisited.items())
# print(node[1])/span>
candidates = [node for node in unvisited.items() if node[1] ]
print(candates)
current, currentDistance = sorted(candidates, key = lambda x: x[1]) [0]
# print(visited) >。
print(dict(sorted)visited.items()))))
TI-Python版本:
ns = ("A"/span>, "B"/span>, "C"/span>, "D"/span>, "E"/span>)
ds = {
"A"/span>: {"B"/span>: 6, "D": 1}。
"B"/span>: {"A"/span>: 6, "C": 5, "D"/span>: 2, "E": 2}。
"C"/span>: {"B"/span>: 5, "E": 5}。
"D"/span>: {"A"/span>: 1, "B": 2, "E": 1}。
"E"/span>: {"B"/span>: 2, "C": 5, "D": 1}。
}
un = {no: None for no in ns}。
vi = {}
cn = "A"/span>
cd = 0
un[cn] = cd
while True:
for ne in sorted(ds[cn])。
di = ds[cn][ne]
if ne not in un。
繼續
nd = cd di
if un[ne] is None or un[ne] > nd:
un[ne] = nd
vi[cn] = cd
del un[cn] 。
if not un:
斷裂。
cs = [no for no in un.items() if no[1] ]
cn, cd = sorted(cs, key=lambda x: x[1]) [0]
print(dict(sorted(vi.items()))))
誰能解釋一下如何重構cs = [no for no in un.items() if no[1]]和print(dict(sorted(vi.items()))))),以便它們不需要.items()或.values(). 方法?
uj5u.com熱心網友回復:
雖然.items()非常有用,但它等同于迭代鍵值,然后查找值。
for k in dict:
v = dict[k] 。
等同于
for k, v in dict.items():
因此,粗略地重構了
cs = [no for no in un.items() if no[1] ]
將是:
cs = [[k, un[k]] for k in un if un[k]]
請注意,原文可以寫成:
cs = [[k,v] for k, v in un.items() if v]
同樣地,
print(dict(sorted(vi.items()))))
直接等同于:
print(dict(sorted([k。vi[k] for k in vi] )
但這不是很可讀的IMHO。 我想做的是:
print({k: vi[k] for k in sorted(vi. keys()})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328604.html
標籤:
下一篇:列印一個沒有括號和小括號的字典
