如何将一个变量的两个参数传递给一个函数?
问题描述:
我已经给了一个实现优先级队列的类,使用函数来评估优先级。如何将一个变量的两个参数传递给一个函数?
class PriorityQueueWithFunction(PriorityQueue):
"""
Implements a priority queue with the same push/pop signature of the
Queue and the Stack classes. This is designed for drop-in replacement for
those two classes. The caller has to provide a priority function, which
extracts each item's priority.
"""
def __init__(self, priorityFunction):
# type: (object) -> object
"priorityFunction (item) -> priority"
self.priorityFunction = priorityFunction # store the priority function
PriorityQueue.__init__(self) # super-class initializer
def push(self, item):
"Adds an item to the queue with priority from the priority function"
PriorityQueue.push(self, item, self.priorityFunction(item))
我也被赋予了优先级函数,我将初始化上面的类。
def manhattanHeuristic(position, problem, info={}):
"The Manhattan distance heuristic for a PositionSearchProblem"
xy1 = position
xy2 = problem.goal
return abs(xy1[0] - xy2[0]) + abs(xy1[1] - xy2[1])
上面的代码给我们,我们不能改变它。我必须创建该PriorityQueueWithFunction类并将一个元素推送给它。 推我的课程的功能上的参数,项目。但是我的PriorityFunction需要2个。 我应该用什么样的论据来将正确的elemnt推入我的课堂,并使我的优先功能正常工作?
这就是我想和我收到编译错误,manhattanHeuristic ...需要两个参数,1中给出
#Creating a queingFn
queuingFn = PriorityQueueWithFunction(heuristic)
Frontier = queuingFn
#Creating the item that needs to be pushed
StartState = problem.getStartState()
StartNode = (StartState,'',0,(-1,-1))
#Here is my problem
item = StartState , problem
Frontier.push(item)
我应该改变我的项目的形式?有任何想法吗 ?
答
你应该把它包装调用manhattanHeuristic的新方法:
# for item as dict: item = {'position': POS, 'problem': PROBLEM}
def oneArgHeuristic(item):
position = item.position
problem = item.problem
return manhattanHeuristic(position, problem)
# for item as tuple: item = (POS, PROBLEM)
def oneArgHeuristic(item):
position, problem = item
return manhattanHeuristic(position, problem)
,并把它传递给PriorityQueueWithFunction
代替原有的一个
看看'* args'和'** kwargs' 。它们允许您使用单个(或两个)变量在函数中传递任意数量的数据。您可以将这些内容解压缩到函数中。 –
在你的情况下,它应该可以像添加一个星号'*'在'item'的infront一样简单。 –