Python:从两个不同的列表中获取两个值
问题描述:
Python是否具有内置方法我可以通过随机方式从两个不同列表中获取两个值?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?
答
如果你想有一个随机配对,您可以使用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)]
答
您可以使用random.choice
做到这一点:
listOne = ['Blue', 'Red', 'Green']
listTwo = [1, 2, 3]
import random
print (random.choice(listOne), random.choice(listTwo))
答
>>> from random import choice
>>> listOne = ['Blue', 'Red', 'Green']
>>> listTwo = [1, 2, 3]
>>> map(choice, (listOne, listTwo))
['Green', 1]
+0
这比我的回答更简洁:) –
- 1没有想到或研究 – Marcin
为什么人们认为应该有一个内置的东西?美丽是有少量的内建可以组合在一起解决问题。 –