如何引用在函数中初始化的列表? (Python)
How can I reference a list initialized in a function? (Python)
我收到的错误是赋值前引用的局部变量 'actions'。我有一种感觉,这是因为我在函数中创建列表,然后尝试在其中引用它。这是我收到错误的具体代码。
if node.state == target:
actions: []
cells: []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent
这是我正在编写的代码来源的更多上下文。
def shortest_path(source, target):
"""
Returns the shortest list of (movie_id, person_id) pairs
that connect the source to the target.
If no possible path, returns None.
"""
# Create a frontier
frontier = QueueFrontier()
# Initialise explored set
explored = set()
# Create a start Node
node = Node(state=source, parent=None, action=None)
# Start with the source as a node (The initial state) and add it to the frontier
frontier.add(node)
# Start looping until we get a solution
while True:
# Check if Frontier is empty then no solution
if frontier.empty():
raise Exception("No path found")
# Remove node from the frontier
node = frontier.remove()
# Check if node contains the goal state
if node.state == target:
actions: []
cells: []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent
actions.reverse()
cells.reverse()
solution = (actions, cells)
return solution
非常感谢您对此提供的帮助。
使用=
赋值
if node.state == target:
actions = []
cells = []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent
我收到的错误是赋值前引用的局部变量 'actions'。我有一种感觉,这是因为我在函数中创建列表,然后尝试在其中引用它。这是我收到错误的具体代码。
if node.state == target:
actions: []
cells: []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent
这是我正在编写的代码来源的更多上下文。
def shortest_path(source, target):
"""
Returns the shortest list of (movie_id, person_id) pairs
that connect the source to the target.
If no possible path, returns None.
"""
# Create a frontier
frontier = QueueFrontier()
# Initialise explored set
explored = set()
# Create a start Node
node = Node(state=source, parent=None, action=None)
# Start with the source as a node (The initial state) and add it to the frontier
frontier.add(node)
# Start looping until we get a solution
while True:
# Check if Frontier is empty then no solution
if frontier.empty():
raise Exception("No path found")
# Remove node from the frontier
node = frontier.remove()
# Check if node contains the goal state
if node.state == target:
actions: []
cells: []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent
actions.reverse()
cells.reverse()
solution = (actions, cells)
return solution
非常感谢您对此提供的帮助。
使用=
赋值
if node.state == target:
actions = []
cells = []
while node.parent is not None:
actions.append(node.action)
cells.append(node.state)
node = node.parent