Странное поведение с циклом while (не так, как ожидалось!) - PullRequest
0 голосов
/ 08 апреля 2019

Я написал короткую программу, которая, по сути, выбирает 3 объекта из 3 списков, индексирует выбор, а затем не может никогда не иметь возможности сделать тот же выбор снова.Это очень близко, единственная проблема вместо того, чтобы никогда не выбирать последовательность снова, она всегда выбирает ту же последовательность?

trial_index = 0 
trials = [None] 

digits = ['0', '1','2','3'] 
word = [ "word1", "word2"]
images = [image1, image2, image3] 

digit_index = random.randint(0,3) 
word_index = random.randint(0,1)
image_index = random.randint(0,2) 

trials[trial_index] = digit_index + word_index + image_index

trial_index+=1 

selected_trial = " " 
selected_trial = trials

# Up until this point behaviour functions as expected I think... 

# This doesn't work, I assumed that what would occur is that as long as this evaluated to TRUE it would run this code forcing it to choose a new sequence? 

while selected_trial in trials: 

    digit_index = random.randint(0,3)
    word_index = random.randint(0,1)
    image_index = random.randint(0,13)
    selected_trial = digit_index + word_index + image_index 
    trials[trial_index] = selected_trial
    trial_index += 1

1 Ответ

1 голос
/ 08 апреля 2019

Используя random.choice Я сделал это проще - и теперь он работает правильно.

import random

digits = ['0', '1','2','3'] 
word   = ['word1', 'word2']
images = ['image1', 'image2', 'image3'] 

trials = []

d = random.choice(digits)
w = random.choice(word)
i = random.choice(images)

trials.append( (d,w,i) )

while (d,w,i) in trials:
    d = random.choice(digits)
    w = random.choice(word)
    i = random.choice(images)

trials.append( (d,w,i) )

print(trials)

РЕДАКТИРОВАТЬ: это работает с индексами

import random

trials = [] 
trial_index = 0 

digits = ['0', '1', '2', '3'] 
word   = [ "word1", "word2"]
images = ['image1', 'image2', 'image3'] 

digit_index = random.randint(0, 3) 
word_index  = random.randint(0, 1)
image_index = random.randint(0, 2) 

selected_trial = (digit_index, word_index, image_index)

trials.append( selected_trial )
trial_index += 1 
#trial_index = len(trials)

while selected_trial in trials: 

    digit_index = random.randint(0, 3)
    word_index  = random.randint(0, 1)
    image_index = random.randint(0, 2)
    selected_trial = (digit_index, word_index, image_index)

trials.append( selected_trial )
trial_index += 1
#trial_index = len(trials)

print( trials )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...