如何从此列表元组返回随机键值?我只关心从动作中返回'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]))
答案 0 :(得分:3)
>>> import random
>>> moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
>>> random.choice(moves)
('s', 'scissors')
如果只需要元组的第一个值:
random.choice(moves)[0]
答案 1 :(得分:1)
>>> 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)]