使用dict(python)中的特定键构建列表? [英] Build a list using specific keys in a dict (python)?
问题描述
path = []
path.append(destination)
previous = predecessor_map [destination ]
while previous!= origin:
path.append(previous)
previous = predecessor_map [previous]
有没有办法用较少的代码行(例如列表理解)?
我唯一的建议是摆脱轻微的代码重复:
path = []
以前=目的地
,而之前!=起始:
path.append(上一个)
上一页=前一个_map [上一页]
除此之外,我认为你的代码实际上很清楚,不可能从任何缩短尝试中获益。
最后,值得注意的是,当 destination == origin
时,以上也可以使用,而您的原始版本最可能不会(取决于如何确定 predece ssor_map
被填充)。不知道这是否与您的用例相关。
I'm implementing the Dijkstra search algorithm in Python. At the end of the search, I reconstruct the shortest path using a predecessor map, starting with the destination node's predecessor. For example:
path = []
path.append(destination)
previous = predecessor_map[destination]
while previous != origin:
path.append(previous)
previous = predecessor_map[previous]
Is there any way to do this with less lines of code (e.g. list comprehension)?
The only suggestion that I have is to get rid of the slight code duplication:
path = []
previous = destination
while previous != origin:
path.append(previous)
previous = predecessor_map[previous]
Beyond that, I think your code is actually very clear and is unlikely to benefit from any attempts to shorten it.
Lastly, it is worth noting that the above also works when destination == origin
, whereas your original version most probably doesn't (depends on how exactly predecessor_map
is populated). Don't know if this is relevant to your use cases.
这篇关于使用dict(python)中的特定键构建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!