-2

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?
4

3 回答 3

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)]
于 2013-05-15T14:09:40.873 回答
3

您可以使用它random.choice来执行此操作:

listOne = ['Blue', 'Red', 'Green']
listTwo = [1, 2, 3]

import random
print (random.choice(listOne), random.choice(listTwo))
于 2013-05-15T14:12:33.570 回答
1
>>> from random import choice
>>> listOne = ['Blue', 'Red', 'Green']
>>> listTwo = [1, 2, 3]
>>> map(choice, (listOne, listTwo))
['Green', 1]
于 2013-05-15T14:15:52.523 回答