我随机抽取两个元创建一个元组列表,像这样:如何从列表中随机选择一个元组?
tuple1 = ('green','yellow','blue','orange','indigo','violet')
tuple2 = ('tree',2,'horse',4,6,1,'banana')
mylist = [(t1,t2) for item1 in tuple1 for item2 in tuple2]
这当然给了我这样的:
[('green','tree'),('yellow', 2)]
等。
但是然后,我想随机从生成的mylist
中选择一个两项目元组。换句话说,返回类似('green',2)
。
如何从列表中随机选择一个两项目元组?我尝试以下,但它不工作:
my_single_tuple = random.choice(mylist.pop())
我会为任何线索或建议表示感谢。
[编辑]我不清楚目标:我想删除(弹出)从列表中随机选择的元组。
执行上述代码的结果:'NameError:name't1'未定义' – RomanPerekhrest
'random.choice'需要一个列表,为什么不只是'my_single_tuple = random.choice(mylist)'? – rodrigo
这应该可能是'mylist = [(item1,item2)for item1 in tuple1 for item2 in tuple2]' –