I would like to choose exactly n items from the Lists (P1,P2,P3). If they are not already in the result list (LIST) they should be appended/extended. If the while loop reaches n (here <=3) it should stop. But I get results with 4,6 items. Why ? Thank you.
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
That is because you check that condition at start of each loop.
At start of the loop condition will be 0, 1, 2 but in the loop you can insert up to 5 new elements, increasing it possibly up to 7.
The while
executes the whole loop, and before starting the next iteration, it checks whether the condition is still true.
Inside of a single iteration of your loop, you extend the list by up to 6 elements.
If you really only want 3 elements, that you would have to check the condition every time you appended something, like so:
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
You check if there are less/equal than 3 Elements in you list
while len(LIST) <=3:
after that, you add up to 5 items before you check again.
so if your last loop got 3 items at its begining and it adds up to 5 items, your list can contain up to 8 Elements.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.