我已经使用Python2.7几个星期了,在下面的循环中需要一些帮助:
nos_rounds = raw_input("Number of rounds?")
student = stu_input(ui)# links to a function to input a list of strings
for x in range(0,int(nos_rounds)):
student2 = randomList(student)#randomising list function
student2 = partition(student,gs)#partitions the randomised list
fcprint(student2)#prints the student list to the console and a file
我遇到的问题是,循环第二次运行时,列表“student”被清除,并放入一个空列表中“学生”一点也不被代码改变。这是怎么回事?我是新的编码,似乎不能解决这个问题。任何帮助都将不胜感激!你知道吗
请求的功能包括:
def randomList(a): # this creates a random list of students on the course
import random
b = []
for i in range(len(a)):
element = random.choice(a)
a.remove(element)
b.append(element)
return b
def partition(lst, n): # this creates sub list of the student list containing the groups of students
increment = len(lst) / float(n)
last = 0
i = 1
results = []
while last < len(lst):
idx = int(round(increment * i))
results.append(lst[last:idx])
last = idx
i += 1
return results
def fcprint(student):#print to the console and then to an external file
floc = raw_input("Input the name of the file")
f = open(floc +".doc", "w")
for item in range (0,len(student)):
print ""
print "Group",item+1, ":\n", "\n".join(student[item])
print >>f, "\n"
print >>f,"Group: ", item+1
print >>f, "\n".join(student[item])
f.close()
谢谢,我试过以下方法:
for x in range(0,int(nos_rounds)):
newstu = student[:]
print "top", newstu
student2 = randomList(newstu)# randomises the student list student is reconised on the first run but is empty on second run
print "bottom", newstu
student2 = partition(student2,gs)# creates the groups
fcprint(student)#prints the student list to the console and a file
还是没法用。输出用于打印语句:
top ['1', '2', '3', '4', '5']
bottom []
得到了论坛的建议。工作版本为:
def randomList(z): # this creates a random list of students on the course
import random
r = z[:]
b = []
for i in range(len(r)):
element = random.choice(r)
r.remove(element)
b.append(element)
return b
for x in range(0,int(nos_rounds)):
student2 = randomList(student)# randomises the student list student is reconised on the first run but is empty on second run
student2 = partition(student2,gs)# creates the groups
fcprint(student2)#prints the student list to the console and a file
问题出在randomList():
在这一行
a.remove(element)
您将从原始列表中删除元素,直到它消失为止。所以在第二次迭代中它将是空的。你知道吗通过@loutre:尝试复制列表(例如a_copy=a[:]),并在函数中使用此副本
相关问题 更多 >
编程相关推荐