2016-12-10 127 views
1

我随机抽取两个元创建一个元组列表,像这样:如何从列表中随机选择一个元组?

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()) 

我会为任何线索或建议表示感谢。

[编辑]我不清楚目标:我想删除(弹出)从列表中随机选择的元组。

+0

执行上述代码的结果:'NameError:name't1'未定义' – RomanPerekhrest

+3

'random.choice'需要一个列表,为什么不只是'my_single_tuple = random.choice(mylist)'? – rodrigo

+0

这应该可能是'mylist = [(item1,item2)for item1 in tuple1 for item2 in tuple2]' –

回答

2

如果你想选择一个元组,然后删除它只是获得索引,然后将其删除。

import random 

tuple1 = ('green','yellow','blue','orange','indigo','violet') 
tuple2 = ('tree',2,'horse',4,6,1,'banana') 

mylist = [(item1,item2) for item1 in tuple1 for item2 in tuple2] 


while len(mylist) > 0: 
    index = random.randint(0,len(mylist)-1) 
    print(mylist[index]) 
    del mylist[index] 
+2

我说,*“这就是为什么字面上有一个'random.randrange'”*。我不确定最后的改变是否有助于解决问题,是否存在'list.pop'问题?一些迹象表明,OP想要完全清除列表并只打印其中的元素? – jonrsharpe

+1

为什么不使用random.shuffle *一次*然后从最后流行元素? –

2

如果你需要这个多次做,只是洗牌的名单一次,然后从前面弹出项目:

random.shuffle(mylist) 
mylist.pop() 
mylist.pop() 

+0

仅当列表的原始顺序无用时才有效。 – jonrsharpe

+0

是的,我正在考虑从列表中弹出随机项目直到列表为空或满足某些条件的场景。 – RemcoGerlich

1

我想我找到问题的答案:

my_item = mylist.pop(random.randrange(len(mylist))) 

这成功地给了我一个随机元组从列表中。谢谢@ philipp-braun,你的回答非常接近,但对我来说不起作用。

相关问题