2017-09-28 26 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

相關問題