使用dict(python)中的特定键构建列表? [英] Build a list using specific keys in a dict (python)?

查看:139
本文介绍了使用dict(python)中的特定键构建列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Python中实现Dijkstra搜索算法。在搜索结束时,我使用前导映射重建最短路径,从目标节点的前身开始。例如:

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆