2017-09-28 23 views
2

我有两份名单,基本上同一个号码:蟒蛇再怎么画一个变量,如果它是另一个相同的变量

import random 

A = [ 0, 10, 20, 30, 40 ] 
B = [ 0, 10, 20, 30, 40 ] 
drawA =(random.choice(A)) 
drawB =(random.choice(B)) # want to exclude the number drawn in drawA 

我怎么能问蟒蛇如果drawB == drawA重新绘制。

否则,如何从列表B中绘制一个数字,但不包括列表A中已绘制的数字?

+0

总是会有'A'和'B' 是相同的? –

+0

为什么不使用'random.shuffle'然后是'list.pop'?或者,'drawA,drawB = random.sample(A,2)'。 –

+0

[**'random.sample' **](https://docs.python.org/2/library/random.html#random.sample)。 –

回答

1

只需从B中排除drawA的值,同时找到随机数。

drawB = random.choice(filter(lambda num: num != drawA, B)) 

OR

不断循环,直到你得到想要的结果。

import random 

A = [ 0, 10, 20, 30, 40 ] 
B = [ 0, 10, 20, 30, 40 ] 

drawA = random.choice(A) 
number = random.choice(B) 
while number == drawA: 
    number = random.choice(B) 

drawB = number 
+0

[**'random' **](https://docs.python.org/2/library/random.html)模块提供了哪些其他选项? –

+0

@PeterWood我得到的抽样可能有效,但如果两个名单不同,会发生什么。 – hspandher

+0

非常感谢你 – Ryan

1

在没有drawA元素的修改数组中搜索。

import random 

A = [ 0, 10, 20, 30, 40 ] 
B = [ 0, 10, 20, 30, 40 ] 
drawA =(random.choice(A)) 
drawB =(random.choice([x for x in B if x != drawA])) 
+0

非常感谢你 – Ryan

1

起初,我们可以创建一个随机数发生器用于B:

def gen_B(): 
    while True: 
     yield random.choice(B) 

,然后选择第一个,是不是用于A值:

drawB = next(x for x in gen_B() if x != drawA) 

或者,您可以使用:

import itertools 
next(x for x in (random.choice(B) for _ in itertools.count()) if x != drawA) 
+0

非常感谢你 – Ryan

相关问题