伪随机化一个没有重复的列表; while 循环效率不高

pseudo-randomize a list without repeats; while loop is not efficient

我正在创建一个具有三个条件 (0,1,2) 的条件实验,并且需要伪随机化条件顺序。我需要一个随机化列表,每个条件只连续出现 2 次。在这里我是如何尝试实现它的。代码是 运行 但它需要一个永恒...

知道为什么这段代码不能很好地工作以及解决问题的不同方法吗?

#create a list with 36 values
types  = [0] * 4 + [1] * 18 + [2]*14 #0=CS+ ohne Verstärkung; 1 = CS-, 2=CS+     mit shock

#random.shuffle(types)

while '1,1,1' or '2,2,2' or '0,0,0' in types:
    random.shuffle(types)
else: print(types)

提前致谢! 玛蒂娜

while '1,1,1' or '2,2,2' or '0,0,0' in types:
    random.shuffle(types)

评估为:

while True or True or '0,0,0' in types:
    random.shuffle(types)

并在 while True

处短路

相反,使用:any() which returns True 如果任何内部项是 True

此外,您的类型是数字,您将其与字符串进行比较:

>>> types
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]

因此您需要将这些数字映射到可以比较的字符串:

>>> ','.join(map(str, types))
'0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2'

尝试:

while any(run in ','.join(map(str, types)) for run in ['0,0,0', '1,1,1', '2,2,2']):
    random.shuffle(types)

>>> types
[1, 2, 1, 2, 1, 2, 1, 1, 0, 2, 0, 1, 2, 1, 1, 2, 1, 2, 1, 2, 2, 1, 1, 2, 0, 2, 1, 1, 0, 2, 1, 1, 2, 2, 1, 1]

你的循环有几个问题。首先 while '1,1,1' or '2,2,2' or '0,0,0' in types:while ('1,1,1') or ('2,2,2') or ('0,0,0' in types): 相同。非零字符串始终为真,因此您的条件始终为真,而 while 永远不会停止。即使是这样,types 也是一个整数列表。 '0,0,0' 是一个字符串,不是列表的元素。

itertools.groupby是解决这个问题的好工具。它是一个迭代器,旨在将序列分组为子迭代器。您可以使用它来查看是否有任何数字簇太长。

import random
import itertools

#create a list with 36 values
types  = [0] * 4 + [1] * 18 + [2]*14 #
print(types)

while True:
    random.shuffle(types)
    # try to find spans that are too long
    for key, subiter in itertools.groupby(types):
        if len(list(subiter)) >= 3:
            break # found one, staty in while 
    else:
        break # found none, leave while

print(types)