我正在创建一个具有三个条件 (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: 与 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)
