Python:根据字典查找最小值
所以这就是我“希望”能够编写的:
cur_loc = min(open_set,key=lambda x:costs[x])
cur_loc
是一个元组,目标是将其设置为等于 open_set
中的元组成本最低。 (您可以使用 costs[x]
找到 x
的成本)
我该怎么做?我尝试了 Python.org 关于 min()
的文档,但似乎没有找到太多帮助。
谢谢!
编辑: 我解决了我自己的问题。
我很迟钝,没有初始化成本字典。我实际上是复制并粘贴别人的 python 代码来测试他们在做什么,但显然他们创建的代码片段不包括初始化部分。糟糕。如果有人有兴趣:
for row in range(self.rows):
for col in range(self.cols):
myloc = (row,col)
if (myloc) not in closed_set:
costs[myloc] = (abs(end_row-row)+abs(end_col - col))*10
if (myloc) not in open_set:
open_set.add(myloc)
parents[myloc] = cur_loc
cur_loc = min(open_set,key=lambda x:costs[x])
So this is what I'd "like" to be able to write:
cur_loc = min(open_set,key=lambda x:costs[x])
cur_loc
is a tuple, and the goal is to set it equal to the tuple in open_set
with the lowest cost. (and you find the cost of x
with costs[x]
)
How could I do this? I tried Python.org's documentation on min()
, but I didn't seem to find much help.
Thanks!
EDIT:
I resolved my own problem.
I was retarded and hadn't initialized the costs dictionary. I was actually copy and pasting someone else's python code in order to test what they were doing, but apparently the snippet they created didn't include the initialization part. Woops. If anyone is interested:
for row in range(self.rows):
for col in range(self.cols):
myloc = (row,col)
if (myloc) not in closed_set:
costs[myloc] = (abs(end_row-row)+abs(end_col - col))*10
if (myloc) not in open_set:
open_set.add(myloc)
parents[myloc] = cur_loc
cur_loc = min(open_set,key=lambda x:costs[x])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
为我工作。你有什么问题?
Worked for me. What's your question?
如果
cost[x]
是以元组为键的字典查找,那么您提供的将是正确的。我认为您可能打算提取元组的字段并查找该字段的成本:The you supplied would be correct if
cost[x]
was a dictionary lookup with tuples as keys. I think you may have meant to extract a field for the tuple and lookup the cost of that field: