Skip to content

Instantly share code, notes, and snippets.

@lhsfcboy
Created June 26, 2017 05:40
Show Gist options
  • Save lhsfcboy/8517b15323eaf442132428d654b541e1 to your computer and use it in GitHub Desktop.
Save lhsfcboy/8517b15323eaf442132428d654b541e1 to your computer and use it in GitHub Desktop.
把函数作为字典的值
moves = ['up', 'left', 'down', 'right']
def move_up(x): # 定义向上的操作
x[1] += 1
def move_down(x): # 定义向下的操作
x[1] -= 1
def move_left(x): # 定义向左的操作
x[0] -= 1
def move_right(x): # 定义向右的操作
x[0] += 1
# 动作和执行的函数关联起来,函数作为键对应的值
actions = {
'up': move_up,
'down': move_down,
'left': move_left,
'right': move_right
}
coord = [0, 0]
for move in moves:
actions[move](coord)
print(coord)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment