感觉还是写的太复杂了,公司另一个人用Stata写的就特别简单。
from openpyxl import load_workbook
import random
from openpyxl import Workbook
def F_generate(l,m,n):
# l, m : row index
#n: number of faculty
wb_in = load_workbook(filename='/Users/Huizhi/Downloads/Sampling/sample_selection_in.xlsx', read_only=True)
wb_out = load_workbook(filename = '/Users/Huizhi/Downloads/Sampling/sample_selection_out.xlsx')
ws_in = wb_in['Tabelle1']
ws_out = wb_out['Sheet1']
Uni,Fakultaet,ins,number = list(),list(),list(),list()
i=0
for row in ws_in.rows:
i+=1
if i>=l and i<=m:
Uni.append(row[0].value)
Fakultaet.append(row[1].value)
ins.append(row[2].value)
number.append(row[3].value)
else :
continue
F = random.sample(set(Fakultaet),n)
choo,choo1,choo2,choo3,choo4 = [],[],[],[],[]
l = []
functions = {'F0': lambda x: choo1.append(x),
'F1': lambda x: choo2.append(x),
'F2': lambda x: choo3.append(x),
'F3': lambda x: choo4.append(x),
}
z = zip(Uni,Fakultaet,ins,number)
for i in z:
l.append(i)
for i in range(len(l)):
if l[i][1] in F:
n = F.index(l[i][1])
func = functions['F'+str(n)]
func(l[i])
choo1 = list(set(choo1))
choo.append(choo1)
choo2 = list(set(choo2))
choo.append(choo2)
choo3 = list(set(choo3))
choo.append(choo3)
choo4 = list(set(choo4))
choo.append(choo4)
return choo
choo = F_generate(305,340,4)
choo
print(choo[0])
ch = choo[0]
x = random.choice(ch)
# ws_out.append(x)
# wb_out.save("/Users/Huizhi/Downloads/Sampling/sample_selection_out.xlsx")
print(x)
summ = int(x[3])
print(summ)
while summ< 5:
if ch:
print(ch)
ch.remove(x)
y = random.choice(ch)
print(y)
# ws_out.append(y)
# wb_out.save("/Users/Huizhi/Downloads/Sampling/sample_selection_out.xlsx")
summ+=int(y[3])
x= y
print(summ)