![](/img/trans.png)
[英]How to stop a random.choice() from choosing in a while loop?
[英]Choosing random items in a while loop does not behave as expected
我想从列表(P1,P2,P3)中选择正好n个项目。 如果它们还不在结果列表(LIST)中,则应附加/扩展它们。 如果while循环达到n(此处<= 3),则应停止。 但是我得到了4,6个项目的结果。 为什么呢 谢谢。
from random import choice
P1 = ["a", "b","c", "d", "e","f","g","h","i","j"]
P2 = ["a","m","b","n","e","z","h","g","f","j"]
P3 = [("a","b"), ("c","e"), ("g","a"), ("m","j"), ("d","f")]
LIST = []
while len(LIST) <=3:
c1, c2 = choice(P3)
d = choice(P1)
e = choice(P2)
f = choice(P1)
g = choice(P2)
if c1 not in LIST and c2 not in LIST:
LIST.extend([c1,c2])
if d not in LIST:
LIST.append(d)
if e not in LIST:
LIST.append(e)
if f not in LIST:
LIST.append(f)
if g not in LIST:
LIST.append(g)
print LIST
这是因为您在每个循环开始时都要检查该条件。
在循环开始时,条件将为0、1、2,但是在循环中,您最多可以插入5个新元素,可能会增加到7。
while
执行整个循环,在开始下一次迭代之前,它将检查条件是否仍然为真。
在循环的一次迭代中,您最多可以将列表扩展6个元素。
如果您确实只需要3个元素,则每次添加内容时都必须检查条件,例如:
while True:
c1,c2 = choice(P3)
d = choice(P1)
e = choice(P2)
f = choice(P1)
g = choice(P2)
if c1 not in LIST and c2 not in LIST:
LIST.append(c1)
if len(LIST) >= 3:
break
LIST.append(c2)
if len(LIST) >= 3:
break
if d not in LIST:
LIST.append(d)
if len(LIST) >= 3:
break
if e not in LIST:
LIST.append(e)
if len(LIST) >= 3:
break
if f not in LIST:
LIST.append(f)
if len(LIST) >= 3:
break
if g not in LIST:
LIST.append(g)
if len(LIST) >= 3:
break
您检查列表中是否少于/等于3个元素
while len(LIST) <=3:
之后,您最多添加5个项目,然后再次检查。
因此,如果您的最后一个循环在开始时有3个项目,并且总共增加了5个项目,则您的列表最多可以包含8个元素。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.