2017-08-26 35 views
0

如何在一次運行中得到此長代碼過程以創建3個試驗而不是一個?重複此過程3次

import numpy 
import math 
import random 
members=4 
n_groups =4 
participants=list(range(1,members+1))*n_groups 
#print participants 
random.shuffle(participants) 

with open('myfile1.txt','w') as tf: 
    for i in range(n_groups): 
     group = participants[i*members:(i+1)*members] 
     for participant in group: 
      tf.write(str(participant)+' ') 
     tf.write('\n') 

with open('myfile1.txt','r') as tf: 
    g = [list(map(int, line.split())) for line in tf.readlines()] 
    print(g) 


my_groups =g 

def get_rating(group): 
    return len(set(group)) 



for each_grp in my_groups: 
    print(get_rating(each_grp)) 

通常的結果是:

[[2, 4, 1, 3], [3, 1, 2, 1], [3, 3, 4, 4], [2, 4, 1, 2]] 
4 
3 
2 
3 

我怎麼能得到這個重複的次數的整個過程n個的過程中它像(如重複3次):

[[3, 1, 2, 3], [4, 2, 1, 1], [2, 3, 1, 4], [4, 4, 3, 2]] 
3 
3 
4 
3 
[[3, 1, 4, 1], [4, 3, 3, 4], [2, 2, 2, 2], [4, 1, 1, 3]] 
3 
2 
1 
3 
[[3, 1, 3, 3], [4, 4, 4, 2], [1, 1, 2, 3], [2, 4, 1, 2]] 
2 
2 
3 
3 

我可以複製代碼3次,但我想知道是否有另一種方式?

+0

把你想重複的代碼在for循環https://wiki.python.org/moin/ForLoop – inarilo

+0

我想重複整個事情,不知道把它放在哪裏或如何 – Xenon

回答

1

只需使用一個循環,並把它的一切:

import numpy 
import math 
import random 
for i in range(3): 
    # everything is in, see the indentation 
    members=4 
    n_groups =4 
    participants=list(range(1,members+1))*n_groups 
    #print participants 
    random.shuffle(participants) 

    with open('myfile1.txt','w') as tf: 
     for i in range(n_groups): 
      group = participants[i*members:(i+1)*members] 
      for participant in group: 
       tf.write(str(participant)+' ') 
      tf.write('\n') 

    with open('myfile1.txt','r') as tf: 
     g = [list(map(int, line.split())) for line in tf.readlines()] 
     print(g) 


    my_groups =g 

    def get_rating(group): 
     return len(set(group)) 

    for each_grp in my_groups: 
     print(get_rating(each_grp)) 

,輸出:

[[3, 4, 2, 1], [3, 2, 2, 1], [1, 3, 4, 4], [3, 2, 1, 4]] 
4 
3 
3 
4 
[[3, 2, 1, 3], [2, 2, 3, 1], [4, 3, 4, 4], [1, 4, 1, 2]] 
3 
3 
2 
3 
[[3, 4, 3, 4], [1, 2, 3, 2], [2, 1, 2, 1], [3, 4, 4, 1]] 
2 
3 
2 
3 
+0

完美!現在馬上改正! – Xenon