伪随机化列表而不重复; while循环效率不高

时间:2017-03-24 18:58:27

标签: python shuffle

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

提前谢谢! 的Martina

2 个答案:

答案 0 :(得分:1)

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()如果任何内部字词为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]

答案 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):相同。非零字符串始终为True,因此您的条件始终为true,而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)