使用Python时清除列表

时间:2016-03-10 13:29:34

标签: python list loops

我已经使用Python 2.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

我遇到的问题是循环第二次运行列表'学生'被清除并进入空列表。 '学生'代码完全没有改变。这里发生了什么?我是编码的新手,似乎无法解决这个问题。任何帮助将不胜感激!

请求的功能是:

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

1 个答案:

答案 0 :(得分:0)

问题出在randomList():

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

在此行a.remove(element),您将从原始列表中删除元素,直到它消失为止。所以在第二次迭代时它将是空的。

@loutre:尝试复制您的列表(例如a_copy = a [:]并在函数内使用此副本