如果不是删除与之前匹配的元素,而是替换它直到它不删除,您的代码将起作用:
from random import randint
guesses = [randint(1,4)]
for x in range (1, 100):
guess = randint(1,4)
guesses.append(guess)
while guesses[x] == guesses[x-1]:
guesses[x] = randint(1,4)
两个替代想法:
您可以创建一组您的选择:
{1, 2, 3, 4}
然后在每次迭代中从集合中请求random.choice - 最后一项。 choice 需要一些可索引的东西,因此您每次都需要转换为列表,但如果这是一个瓶颈,可能有一些方法可以提高效率:
from random import choice
choices = {1, 2, 3, 4}
l = [choice(list(choices))] # start with one random choice
for i in range(99):
l.append(choice(list(choices - {l[-1]})))
这似乎很统一:
from collections import Counter
counts = Counter(l)
counts
Counter({3: 26, 2: 25, 1: 26, 4: 23})
使用迭代器
您可以使用延迟评估的迭代器来完成这一切,然后只需获取所需长度的 islice():
from random import randint
from itertools import tee, islice
#generator to makes random ints between start and stop
def randIt(start, stop):
while True:
yield randint(1,4)
rands, prevs = tee(randIt(1, 4))
next(prevs)
# non_dupes is a generator that makes non-repeating rands
non_dupes = (r for r, i in zip(rands, prevs) if r!=i)
# use itertools islice or a loop to get the number you want
# or just call `next(non_dupes)` for one:
list(islice(non_dupes, 0, 100))