2017-03-24 45 views
2

我正在創建一個具有三個條件(0,1,2)的條件實驗,並且需要對條件順序進行僞隨機化。我需要一個隨機列表,每個條件連續出現兩次。在這裏,我試圖實現它。該代碼正在運行,但它需要一個永恆...僞隨機化一個列表而不重複; while循環效率不高

任何想法,爲什麼此代碼不能很好地工作,以及任何不同的方法來解決問題?

#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) 

預先感謝您! 馬丁娜

+0

連續兩次或最多連續兩次? – tdelaney

+0

另一個類似的問題:http://stackoverflow.com/questions/3313590/check-for-presence-of-a-sliced-list-in-python –

回答

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):相同。非零字符串始終爲真,因此您的條件始終爲真,並且永不停止。即使這樣做,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) 
+0

真酷!它完全解決了我的問題!以前從未聽說過itertools模塊......瞭解了很多! ;) –

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] 
+0

謝謝!這也是一個很好的解決方案!作爲一個總的python初學者,我並不真正瞭解map-function在做什麼。它是否將「str」應用於列表類型中的每個元素?那麼它迭代所有項目還是地圖函數的工作方式不同? –

+0

@MartinaTakeaway是的,[map()](https://docs.python.org/2/library/functions.html#map)將給定的函數應用於提供的迭代器中的每個項目。 – TemporalWolf