如何从此列表元组返回随机键值?我只关心从移动中返回“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]))
如何从此列表元组返回随机键值?我只关心从移动中返回“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]))
>>> import random
>>> moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
>>> random.choice(moves)
('s', 'scissors')
如果只需要元组的第一个值:
random.choice(moves)[0]
>>> import random
>>> moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
>>> print random.choice(moves)[0]
's'
import random
moves = [('r', "rock"), ('p', "paper"), ('s', "scissors")]
move_keys = [ x[0] for x in moves ]
print random.choice(move_keys)
使用随机模块。
random.choice(A)
或者A[random.randint(0,len(A)-1)]