Python的随机委托从一个列表值到另一个
问题描述:
我有两个列表Python的随机委托从一个列表值到另一个
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
什么是随机从b_list极大的元组在一个新的列表委派列表值的最佳方式:
c_list = [('a','1'), ('b','3'), ('c','1')]
答
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
print [(a,random.choice(b_list)) for a in a_list]
输出:
[('a', '3'), ('b', '1'), ('c', '3')]
答
将这些清单和zip
混淆后,他们将完成您的工作。
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
random.shuffle(a_list)
random.shuffle(b_list)
c_list = zip(a_list, b_list)
或者,如果你不希望一对一的映射,那么你也可以使用:
import random
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
c_list = [(i, random.choice(b_list)) for i in a_list]
答
在你的输出,我可以看到重复的值。在下面使用。
没有重复:
random.shuffle(b_list)
print zip(a_list, b_list)
随着重复:
print [ (i,random.choice(b_list)) for i in a_list ]
答
import random
from functools import partial
a_list = ['a', 'b', 'c']
b_list = ['1', '2', '3']
r= partial(random.choice,b_list)
list(zip(a_list,[r(),r(),r()]))
[('a', '1'), ('b', '2'), ('c', '2')]
我认为这个问题会帮助你:http://*.com/questions/306400/how-do-i-randomly-select-an-item-from-a-list-using-python – Thargor
你不用'2' from b_list,是预期的还是你想使用所有的值? – Andy
听起来像一个家庭作品,你有没有尝试过目前为止找出答案? – Kasramvd