我编写了一个简短的程序,该程序实际上是从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
答案 0 :(得分:1)
Using random.choice
I made it simpler - and now it works correctly.
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)
EDIT: this works with indexes
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 )