Python是否有内置方法我可以随机从两个不同的列表中获取几个值?
例如:
listOne = ['Blue', 'Red', 'Green']
listTwo = [1, 2, 3]
# I want to get the result:
# ('Blue',3),('Red',2),('Green',1)
# or ('Blue',2),('Red',3),('Green',1)
# or ('Blue',1),('Red',2),('Green',3)
# and so on...how can I use a method get this result in a random way?
答案 0 :(得分:4)
如果您想要随机配对,可以使用random.shuffle()
:
>>> import random
>>> listOne = ['Blue', 'Red', 'Green']
>>> listTwo = [1, 2, 3]
>>> random.shuffle(listTwo)
>>> zip(listOne, listTwo)
[('Blue', 3), ('Red', 2), ('Green', 1)]
>>> random.shuffle(listTwo)
>>> zip(listOne, listTwo)
[('Blue', 2), ('Red', 1), ('Green', 3)]
答案 1 :(得分:3)
您可以使用random.choice
执行此操作:
listOne = ['Blue', 'Red', 'Green']
listTwo = [1, 2, 3]
import random
print (random.choice(listOne), random.choice(listTwo))
答案 2 :(得分:1)
>>> from random import choice
>>> listOne = ['Blue', 'Red', 'Green']
>>> listTwo = [1, 2, 3]
>>> map(choice, (listOne, listTwo))
['Green', 1]