我可以使用参数来引用变量吗?

时间:2018-01-27 04:45:50

标签: python python-3.x

def rock_paper_scissors_lizard_spock(player1, player2):

    # each variable stores what it can defeat
    scissors = ['paper','lizard']
    rock = ['lizard', 'scissors']
    paper = ['rock','spock']
    lizard = ['spock','paper']
    spock = ['scissors','rock']


    if str(player2) in player1:
        print('player 1 wins')


rock_paper_scissors_lizard_spock('rock','spock')

我可以使用上面声明的函数的参数来引用特定的变量吗?

1 个答案:

答案 0 :(得分:2)

简短的回答,没有。使用字典。

def rock_paper_scissors_lizard_spock(player1, player2):

    # each variable stores what it can defeat
    mapper = {'scissors': ['paper', 'lizard'],
              'rock': ['lizard', 'scissors'],
              'paper': ['rock', 'spock'],
              'lizard': ['spock', 'paper'],
              'spock': ['scissors', 'rock']}

    print('player %s wins' %(1 if player2 in mapper[player1] else 2))

rock_paper_scissors_lizard_spock('paper', 'rock')  # player 1 wins