2

如何从此列表元组返回随机键值?我只关心从移动中返回“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

4 回答 4

3

使用random.choice.

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

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

random.choice(moves)[0]
于 2013-07-25T23:05:11.273 回答
1

使用random.choice.

>>> import random
>>> moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
>>> print random.choice(moves)[0] 
's'
于 2013-07-25T23:06:08.010 回答
0
import random
moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
move_keys = [ x[0] for x in moves ]

print random.choice(move_keys)
于 2013-07-25T23:07:29.783 回答
0

使用随机模块。

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

于 2013-07-25T23:18:50.620 回答