从列表元组返回随机值

时间:2013-07-25 23:04:04

标签: python

如何从此列表元组返回随机键值?我只关心从动作中返回'r','p'或's'。

# Snippet

moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]

view_all(moves):
    print "Player moves:"
    for move in moves:
        print " => ".join((move[0], move[1]))

4 个答案:

答案 0 :(得分:3)

使用random.choice

>>> import random
>>> moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
>>> random.choice(moves)
('s', 'scissors')

如果只需要元组的第一个值:

random.choice(moves)[0]

答案 1 :(得分:1)

使用random.choice

>>> import random
>>> moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
>>> print random.choice(moves)[0] 
's'

答案 2 :(得分:0)

import random
moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
move_keys = [ x[0] for x in moves ]

print random.choice(move_keys)

答案 3 :(得分:0)

使用random模块。

random.choice(A)A[random.randint(0,len(A)-1)]