如何通过这个长代码流程来创建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
我怎么能让这个重复整个过程多次,所以它给出类似的东西(例如重复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 :(得分: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