python - 列表列表之间的最短路径
问题描述
假设我有一个这样的列表:
[
[1, [2, 3]],
[2, [4, 5]],
[4, [6, 7]],
[3, [7]]
]
我想编写可以找到从1
到的最短路径的代码7
,在这种情况下,它将是1 -> 3 -> 7
。
这是我到目前为止所拥有的:
start = 1
lst = [[1, [2, 3]], [2, [4, 5]], [4, [6, 7]], [3, [7]]]
def getIt(start):
for nest in lst:
if start == lst[0]:
return(nest[1])
allLists = []
loopCleaner = []
def travel(paths, totalList):
if paths is not None:
if 7 in paths:
allLists.append(totalList)
else:
for path in paths:
if path not in loopCleaner:
loopCleaner.append(path)
totalList.append(path)
travel(getIt(path), totalList)
print(travel(lst, []))
我正在通过递归和循环的混合来尝试这个,但它要么输出太长的路径,要么只是没有输出。
我的逻辑: 获取所有可能的嵌套列表getIt
。
然后通过递归遍历这些并在它下降时继续添加到总列表,直到在其中一个路径中找到 7。在这种情况下,我们结束并退出。我如何以一种简单的方式编码[1, 3, 7]
?
解决方案
您可以将递归与生成器一起使用:
def paths(d, start, end, c = [], seen=[]):
if end in d.get(start, []):
yield c+[end]
else:
for i in filter(lambda x:x not in seen, d.get(start, [])):
yield from paths(d, i, end, c = c+[i], seen=seen+[i])
data = [[1, [2, 3]], [2, [4, 5]], [4, [6, 7]], [3, [7]]]
print(min(list(paths(dict(data), 1, 7, c=[1])), key=len))
输出:
[1, 3, 7]
推荐阅读
- excel - 如何在 32 位或 64 位 Excel VBA 上使用 Windows SHBrowseforFolder 函数
- javascript - JavaScripts 的 JSON.stringify() / PHP 的 json_decode 使用是不必要的吗?
- linux - 将字符串的最后一个单词从一个文件移动到另一个文件
- python - 在列表中查找数据并在另一个列表中使用
- java - Java EE 构造函数注入 - 如何设置字段?
- ios - 当按下不同 UITableView 单元格中的另一个播放按钮时,如何自动停止当前播放音频?- 斯威夫特
- certificate - 如何使用 TPM 2 作为 Windows 10 中的非对称密钥提供程序生成证书签名请求?
- c# - ASP.NET:如何在不更改浏览器中的 URL 的情况下进行重定向?
- elasticsearch - 删除后正在重新创建 K8S 中的状态集
- python - 如何在python中的列中使用if条件