【问题标题】:python how to draw a variable again if it is the same as another variable如果变量与另一个变量相同,python如何再次绘制变量
【发布时间】:2018-03-10 00:17:59
【问题描述】:

我有两张单子,号码基本一样:

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,如何让python重新绘制。

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

【问题讨论】:

  • AB 总是一样吗?
  • 为什么不直接使用random.shuffle,后跟list.pop?或者,drawA, drawB = random.sample(A, 2)
  • @PeterWood:只有在A == B 时才有效。
  • @EricDuminil AB 相同,OP 没有另外澄清。

标签: python random while-loop draw


【解决方案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)

【讨论】:

    【解决方案2】:

    在没有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]))
    

    【讨论】:

      【解决方案3】:

      在寻找随机数的同时,从B中排除drawA的值。

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

      继续循环,直到获得所需的结果。

      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
      

      【讨论】:

      • random 模块还提供哪些其他选项?
      • @PeterWood 我得到的抽样可能有效,但如果两个列表不同怎么办。
      猜你喜欢
      • 1970-01-01
      • 2021-11-26
      • 2015-03-03
      • 2023-03-31
      • 2020-09-30
      • 2013-08-02
      • 2023-02-09
      • 2011-08-31
      • 2016-11-12
      相关资源
      最近更新 更多