I found the function pop()
, which will remove a single value from a list. However, I want to remove two values from the list - randomly, but both numbers must be adjacent. For example, in a list of [1, 2, 3, 4, 5]
, if I randomly picked 2
with pop()
, I'd also want to remove 1
or 3
.
I need to store the numbers (p and q) for a later calculation, here's my code so far:
nlist = [1, 2, 3, 4, 5]
shuffle(nlist)
while nlist:
p = nlist.pop(random.randrange(len(nlist)))
#save p and one adjacent value (q) within this loop
#remove p and q from list
You could choose the randrange
to be across one less than the list's length, and then pop the same index twice:
pop_index = random.randrange(len(nlist)-1)
p = nlist.pop(pop_index)
q = nlist.pop(pop_index)
You need to handle some edge cases when removing your elements, namely when the p
is the first or last element in the list. This uses a handy random
function, choice
to determine which adjacent element you choose.
while len(nlist) > 1:
# the number to remove
p_index = random.randrange(len(nlist))
if p_index == 0:
q_index = p_index + 1
elif p_index == len(nlist) - 1:
q_index = p_index - 1
else:
q_index = p_index + random.choice([-1, 1])
p, q = nlist[p_index], nlist[q_index]
nlist.pop(p_index)
nlist.pop(q_index)
return p, q
You can try this approach:
from random import randint
nlist = [1, 2, 3, 4, 5]
data=randint(0,len(nlist)-2)
print([j for i,j in enumerate(nlist) if i not in range(data,data+2)])
output:
#[3, 4, 5]
#[1, 4, 5]
#[1, 2, 5]
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.